﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using CrystalDecisions.ReportSource;
using C1.Win.C1FlexGrid;
using System.Collections;
using BHXH_NT.Properties;
using Microsoft.VisualBasic;
using BHXH_NT.Data;


namespace BHXH_NT
{
    public partial class FrmInToRoi : Form
    {
        private string connectionString1 = global::BHXH_NT.Properties.Settings.Default.MISBHXH_NTConnectionString1;
        private string connectionString = global::BHXH_NT.Properties.Settings.Default.MISBHXH_NTConnectionString;
        private Int16 flageFlex = 0;
        private InToRoi dsIntoroi = new InToRoi();
        private QuatrinhBHXH dsKQuatrinh = new QuatrinhBHXH();
        private int intSochay = 0;
      
        Random rnd = new Random();
        #region "Event Method"
        public FrmInToRoi()
        {
            InitializeComponent();
        }
        /// <summary>
        /// hien thi so lieu in to roi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSolieu_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            string queryString;
            int i = 1;
            flageFlex = 0;
            queryString = "exec sp_executesql N'SELECT Intr_hdr.KEYSL, Intr_hdr.SOBHXH,"
            + " Intr_hdr.HO, Intr_hdr.TEN, Intr_hdr.MADVI, Intr_hdr.DTDONVI,"
            + " Intr_hdr.LOAIIN, Intr_hdr.LOAI, Intr_hdr.NGAYCAP, Intr_hdr.THANGBD,"
            + " Intr_hdr.THANGKT, Intr_hdr.THANGHT, Intr_hdr.LOAIXN, Intr_hdr.TUTHANGXN,"
            + " Intr_hdr.DENTHANGXN, Intr_hdr.SONAMXN, Intr_hdr.SOTHANGXN, Intr_hdr.TT_XNTNG,"
            + " Intr_hdr.DT_XNTNG, Intr_hdr.SN_XNTNG, Intr_hdr.ST_XNTNG, Intr_hdr.LANCAP,"
            + " Intr_hdr.MACL, Intr_hdr.DAIN, Intr_hdr.NGAYIN, Intr_hdr.USERIN,"
            + " Intr_hdr.DACAP, Intr_hdr.THUHOI, Intr_hdr.NGAYTH, Intr_hdr.CHON,"
            + " Intr_hdr.MAPB, Intr_hdr.USERCODE, Intr_hdr.MA_QUAN, Intr_hdr.LOAIDC,"
            + " a.NGAYSINH,a.GIOITINH,SOCMND,NGAYCMND,NOICAP,MACV,DANTOC,NOIKHAI,QUOCTICH,b.Tendvi,b.Diachi "
            + " FROM  dbo.INTR_HDR Intr_hdr INNER JOIN MISBHXH_NT.DBO.HOSOCN a on a.sobhxh = Intr_hdr.sobhxh "
            + " inner join MISBHXH_NT.DBO.DMDONVI b on Intr_hdr.Madvi = b.Madvi"
            + " WHERE Intr_hdr.USERCODE = ''" + ModuleBHXH.strUser + "'' and Intr_hdr.NGAYIN is null and ( ( (";
            //trương hop them ma don vi
            if (txtMadvi.Text == "")
            {
                queryString = queryString + " Intr_hdr.NGAYCAP >= ( @P2  ) ) AND  Intr_hdr.NGAYCAP <= ( @P3  ) ) AND  Intr_hdr.LOAI = ( @P4  ) )"
                + " order by Intr_hdr.KEYSL', N'@P2 datetime,@P3 datetime,@P4 varchar(1)',"
                + " '" + string.Format("{0:00}", Convert.ToDateTime(dtTungay.Value).Month) + "/" + Convert.ToDateTime(dtTungay.Value).Day + "/"
                + Convert.ToDateTime(dtDenngay.Value).Year + "', '" + string.Format("{0:00}", Convert.ToDateTime(dtDenngay.Value).Month) + "/" + Convert.ToDateTime(dtDenngay.Value).Day + "/" + Convert.ToDateTime(dtDenngay.Value).Year + "', '1'";
                //AND  Intr_hdr.LOAIXN <> ( '''' )
            }
            else
            {
                queryString = queryString + " Intr_hdr.NGAYCAP >= ( @P2  ) ) AND  Intr_hdr.NGAYCAP <= ( @P3  ) ) AND  Intr_hdr.LOAI = ( @P4  ) )"
                + " AND Intr_hdr.Madvi = @P5 order by Intr_hdr.KEYSL', N'@P2 datetime,@P3 datetime,@P4 varchar(1),@P5 varchar(8)',"
                + " '" + string.Format("{0:00}", Convert.ToDateTime(dtTungay.Value).Month) + "/" + Convert.ToDateTime(dtTungay.Value).Day + "/"
                + Convert.ToDateTime(dtDenngay.Value).Year + "', '" + string.Format("{0:00}", Convert.ToDateTime(dtDenngay.Value).Month) + "/" + Convert.ToDateTime(dtDenngay.Value).Day + "/" + Convert.ToDateTime(dtDenngay.Value).Year + "', '1','" + txtMadvi.Text + "A" + "'";
                 //Intr_hdr.LOAIXN <> ( '''' ) and 
            }

            FlxDetail.Rows.Count = 1;
            using (SqlConnection connection =
                  new SqlConnection(connectionString1))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = queryString;
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    FlxDetail.Rows.Count = FlxDetail.Rows.Count + 1;
                    FlxDetail.Rows[i]["CHECK"] = 1;
                    FlxDetail.Rows[i]["STT"] = FlxDetail.Rows.Count;
                    FlxDetail.Rows[i]["KEYSL"] = reader["KEYSL"];
                    FlxDetail.Rows[i]["NgayCap"] = reader["NgayCap"];
                    FlxDetail.Rows[i]["Madvi"] = reader["Madvi"];
                    FlxDetail.Rows[i]["Sobhxh"] = reader["Sobhxh"];
                    FlxDetail.Rows[i]["Ho"] = reader["Ho"];
                    FlxDetail.Rows[i]["Ten"] = reader["Ten"];

                    FlxDetail.Rows[i]["tuthang"] = reader["thangbd"];
                    FlxDetail.Rows[i]["denthang"] = reader["thangkt"];
                    FlxDetail.Rows[i]["dongden"] = reader["thanght"];

                    FlxDetail.Rows[i]["xacnhan"] = reader["loaixn"];
                    FlxDetail.Rows[i]["tuthangxn"] = reader["tuthangxn"];
                    FlxDetail.Rows[i]["denthangxn"] = reader["denthangxn"];
                    FlxDetail.Rows[i]["sonam"] = reader["sonamxn"];
                    FlxDetail.Rows[i]["sothang"] = reader["sothangxn"];


                    FlxDetail.Rows[i]["tuthangxntn"] = reader["TT_XNTNG"];
                    FlxDetail.Rows[i]["denthangxntn"] = reader["DT_XNTNG"];
                    FlxDetail.Rows[i]["sonamtn"] = reader["SN_XNTNG"];
                    FlxDetail.Rows[i]["sothangtn"] = reader["ST_XNTNG"];

                    FlxDetail.Rows[i]["ngayin"] = reader["ngayin"];
                    FlxDetail.Rows[i]["GIOITINH"] = reader["GIOITINH"];
                    if (reader["NGAYSINH"].ToString() != "")
                    {
                        FlxDetail.Rows[i]["NGAYSINH"] = reader["NGAYSINH"].ToString().Substring(0, 10);
                    }
                    FlxDetail.Rows[i]["SOCMND"] = reader["SOCMND"];
                    if (reader["NGAYCMND"].ToString() != "")
                    {
                        FlxDetail.Rows[i]["NGAYCMND"] = reader["NGAYCMND"].ToString().Substring(0, 10);
                    }
                    FlxDetail.Rows[i]["NOICAP"] = reader["NOICAP"];
                    FlxDetail.Rows[i]["DIACHI"] = reader["DIACHI"];
                    FlxDetail.Rows[i]["MACV"] = reader["MACV"];
                    FlxDetail.Rows[i]["DANTOC"] = "Kinh"; //reader["DANTOC"];
                    FlxDetail.Rows[i]["NOIKHAI"] = reader["NOIKHAI"];
                    FlxDetail.Rows[i]["QUOCTICH"] = "ViÖt Nam"; // reader["QUOCTICH"];
                    FlxDetail.Rows[i]["Tendvi"] = reader["Tendvi"]; ; // reader["QUOCTICH"];

                    i++;

                }
                reader.Close();
            }
            CheckDieuChinh();
            Cursor.Current = Cursors.Default;
            flageFlex = 1;
        }
        /// <summary>
        /// hien thi chi tiet tung dong qua trinh
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FlxDetail_AfterRowColChange(object sender, RangeEventArgs e)
        {
            string queryString;
            int i = 1;
            if (flageFlex == 0 || FlxDetail.Selection.TopRow < 0) { return; }
            else if (flageFlex == 2 )
            {
                GetRow(FlxDetail.Rows[FlxDetail.Selection.TopRow]["sobhxh"].ToString(), FlxDetail.Rows[FlxDetail.Selection.TopRow]["tuthang"].ToString());
            }
            else
            {
                queryString = "exec sp_executesql N'SELECT Intr_dtl.KEYSL, Intr_dtl.KEYP, Intr_dtl.MADVI, Intr_dtl.TUTHANG,  Intr_dtl.DENTHANG, "
                + " Intr_dtl.LOAIDT, Intr_dtl.MA_NTE, Intr_dtl.PA,  Intr_dtl.ML, Intr_dtl.HSL, Intr_dtl.PC1, Intr_dtl.PC2, Intr_dtl.PC3,  "
                + " Intr_dtl.PC4, Intr_dtl.TYLE_BHXH, Intr_dtl.TYLE_BHTN, Intr_dtl.NOIDUNG,  Intr_dtl.KIEMTRA, Intr_dtl.MA_QUAN, "
                + " Intr_dtl.USERCODE FROM dbo.INTR_DTL Intr_dtl WHERE Intr_dtl.KEYSL = @P1    "
                + " AND Intr_dtl.TYLE_BHTN = 0 order by Intr_dtl.TUTHANG', N'@P1 varchar(22)', '" + FlxDetail.Rows[FlxDetail.Selection.TopRow]["KEYSL"] + "'";
                faQuaTrinh.Rows.Count = 1;
                using (SqlConnection connection =
                      new SqlConnection(connectionString1))
                {
                    SqlCommand command = connection.CreateCommand();
                    command.CommandText = queryString;
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {

                        faQuaTrinh.Rows.Count = faQuaTrinh.Rows.Count + 1;
                        faQuaTrinh.Rows[i]["Madvi"] = reader["Madvi"];
                        faQuaTrinh.Rows[i]["TuThang"] = reader["Tuthang"].ToString();
                        faQuaTrinh.Rows[i]["DenThang"] = reader["DenThang"].ToString();
                        faQuaTrinh.Rows[i]["Loai"] = reader["Loaidt"];
                        faQuaTrinh.Rows[i]["LoaiTT"] = reader["Ma_nte"];


                        if (Convert.ToDouble(reader["ML"]) != 0) { faQuaTrinh.Rows[i]["MUCLUONG"] = reader["ML"]; }
                        if (Convert.ToDouble(reader["HSL"]) != 0) { faQuaTrinh.Rows[i]["HSL"] = reader["HSL"]; }
                        if (Convert.ToDouble(reader["pc1"]) != 0) { faQuaTrinh.Rows[i]["PCCV"] = reader["pc1"]; }
                        if (Convert.ToDouble(reader["pc2"]) != 0) { faQuaTrinh.Rows[i]["PCTN"] = reader["pc2"]; }
                        if (Convert.ToDouble(reader["pc3"]) != 0) { faQuaTrinh.Rows[i]["PCNG"] = reader["pc3"]; }
                        if (Convert.ToDouble(reader["pc4"]) != 0) { faQuaTrinh.Rows[i]["PCKV"] = reader["pc4"]; }

                        faQuaTrinh.Rows[i]["Congviec"] = reader["Noidung"];

                        i++;

                    }
                    reader.Close();
                }
            }
        }
        /// <summary>
        /// in to roi 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInso_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            DataRow newRow = null, oldrow = null;
            SqlDataReader reader;
            int nam = 0, thang = 0, namtn = 0, thangtn = 0, range = 0;
            dsIntoroi.Clear();
            String queryString;
            try
            {
                using (SqlConnection connection =
                     new SqlConnection(connectionString1))
                {
                    SqlCommand command = connection.CreateCommand();
                    connection.Open();
                    for (int i = 1; i < FlxDetail.Rows.Count; i++)
                    {
                        if (Convert.ToInt16(FlxDetail.Rows[i]["CHECK"]) == 1)
                        {
                            range = dsIntoroi.Tables[0].Rows.Count;
                            nam = 0; thang = 0; namtn = 0; thangtn = 0;
                            //TRUONG HOP BHXH
                            queryString = "exec sp_executesql N'SELECT Intr_dtl.KEYSL, Intr_dtl.KEYP, Intr_dtl.MADVI, Intr_dtl.TUTHANG,  Intr_dtl.DENTHANG, "
                            + " Intr_dtl.LOAIDT, Intr_dtl.MA_NTE, Intr_dtl.PA,  Intr_dtl.ML, Intr_dtl.HSL, Intr_dtl.PC1, Intr_dtl.PC2, Intr_dtl.PC3,  "
                            + " Intr_dtl.PC4, Intr_dtl.TYLE_BHXH, Intr_dtl.TYLE_BHTN, Intr_dtl.NOIDUNG,  Intr_dtl.KIEMTRA, Intr_dtl.MA_QUAN, "
                            + " Intr_dtl.USERCODE FROM dbo.INTR_DTL Intr_dtl WHERE Intr_dtl.KEYSL = @P1    "
                            + " AND Intr_dtl.TYLE_BHTN = 0 order by Intr_dtl.TUTHANG', N'@P1 varchar(22)', '" + FlxDetail.Rows[i]["KEYSL"] + "'";
                            command.CommandText = queryString;
                            reader = command.ExecuteReader();
                            while (reader.Read())
                            {
                                newRow = dsIntoroi.Tables[0].NewRow();
                                newRow["KEYSL"] = FlxDetail.Rows[i]["KEYSL"];
                                newRow["SOBHXH"] = FlxDetail.Rows[i]["SOBHXH"];
                                newRow["HOTEN"] = FlxDetail.Rows[i]["HO"].ToString().Trim() + " " + FlxDetail.Rows[i]["TEN"].ToString().Trim();
                                newRow["TUTHANG"] = ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["TUTHANG"].ToString());
                                newRow["DENTHANG"] = ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["DENTHANG"].ToString());
                                newRow["LOAIXN"] = FlxDetail.Rows[i]["XACNHAN"].ToString();

                                newRow["TTCHITIET"] = ModuleBHXH.FormatThangNam(reader["TUTHANG"].ToString());
                                newRow["DTCHITIET"] = ModuleBHXH.FormatThangNam(reader["DENTHANG"].ToString());
                                newRow["NOIDUNG"] = reader["NOIDUNG"].ToString().Trim().Substring(0, 1).ToUpper() + reader["NOIDUNG"].ToString().Trim().Substring(1);
                                if (FlxDetail.Rows[i]["XACNHAN"].ToString() == "QT")
                                {
                                    newRow["TTDT"] = "Tõ Th¸ng " + newRow["TUTHANG"].ToString() + " §Õn Th¸ng " + newRow["DENTHANG"];
                                }
                                else if (FlxDetail.Rows[i]["XACNHAN"].ToString().Trim() == "")
                                {
                                    newRow["TTDT"] = "N¨m : " + FlxDetail.Rows[i]["denthang"].ToString().Substring(0, 4);
                                }
                                else
                                {
                                    newRow["TTDT"] = "N¨m : " + FlxDetail.Rows[i]["denthangxn"].ToString().Substring(0, 4);
                                }
                                //phan tram bhxh
                                if (Convert.ToInt16(reader["TYLE_BHXH"]) != 0)
                                {
                                    newRow["TLBHXH"] = string.Format("{0:##}", reader["TYLE_BHXH"]) + "%";
                                }
                                //PC1
                                if (Convert.ToDouble(reader["PC1"]) > 0)
                                {
                                    newRow["LOAIPC"] = "CV";
                                    newRow["MUCPC"] = String.Format("{0:0.00}", reader["PC1"]);
                                    if (Convert.ToDouble(reader["PC2"]) > 0)
                                    {
                                        newRow["LOAIPC"] = newRow["LOAIPC"] + Environment.NewLine + "TV";
                                        newRow["MUCPC"] = newRow["MUCPC"] + Environment.NewLine + Convert.ToInt16(Convert.ToDouble(reader["PC2"]) * 100 / Convert.ToDouble(reader["HSL"])).ToString() + "%";
                                    }
                                    if (Convert.ToDouble(reader["PC3"]) > 0)
                                    {
                                        newRow["LOAIPC"] = newRow["LOAIPC"] + Environment.NewLine + "TN";
                                        newRow["MUCPC"] = newRow["MUCPC"] + Environment.NewLine + 
                                            Convert.ToInt16(Convert.ToDouble(reader["PC3"]) * 100 /
                                            (Convert.ToDouble(reader["HSL"]) + Convert.ToDouble(reader["PC2"]) +
                                            Convert.ToDouble(reader["PC1"]))).ToString() + "%";
                                    }
                                }
                                //PC2
                                else if (Convert.ToDouble(reader["PC2"]) > 0)
                                {
                                    newRow["LOAIPC"] = "TV";
                                    newRow["MUCPC"] = Convert.ToInt16(Convert.ToDouble(reader["PC2"]) * 100 / Convert.ToDouble(reader["HSL"])).ToString() + "%";
                                    if (Convert.ToDouble(reader["PC3"]) > 0)
                                    {
                                        newRow["LOAIPC"] = newRow["LOAIPC"] + Environment.NewLine + "TN";
                                        newRow["MUCPC"] = newRow["MUCPC"] + Environment.NewLine +
                                            Convert.ToInt16(Convert.ToDouble(reader["PC3"]) * 100 /
                                            (Convert.ToDouble(reader["HSL"]) + Convert.ToDouble(reader["PC2"]) +
                                            Convert.ToDouble(reader["PC1"]))).ToString() + "%";
                                    }
                                }
                                //PC3
                                else if (Convert.ToDouble(reader["PC3"]) > 0)
                                {

                                    newRow["LOAIPC"] ="TN";
                                    newRow["MUCPC"] = Convert.ToInt16(Convert.ToDouble(reader["PC3"]) * 100 /
                                        Convert.ToDouble(reader["HSL"])).ToString() + "%";
                                }
                                //tinh thoi gian cong tac
                                // truong hop CT, HAY ML,HSL = 0
                                if (reader["LOAIDT"].ToString() == "CT" || (reader["LOAIDT"].ToString() == "ML" && Convert.ToInt32(reader["ML"]) == 0 && reader["PA"].ToString() != "TS") || (reader["LOAIDT"].ToString() == "HS" && Convert.ToInt32(reader["HSL"]) == 0 && reader["PA"].ToString() != "TS"))
                                {
                                    //ModuleBHXH.KhoangThoiGian(newRow["TTCHITIET"].ToString(), newRow["DTCHITIET"].ToString(), ref nam, ref thang);
                                }
                                else
                                {
                                    //ML
                                    if (Convert.ToInt32(reader["ML"]) != 0)
                                    {
                                        newRow["ML"] = string.Format("{0:###,##}", Convert.ToInt32(reader["ML"]));
                                        ModuleBHXH.KhoangThoiGian(newRow["TTCHITIET"].ToString(), newRow["DTCHITIET"].ToString(), ref nam, ref thang);
                                    }
                                    //HSL
                                    else if (Convert.ToInt32(reader["HSL"]) != 0)
                                    {
                                        newRow["ML"] = string.Format("{0:###,##.000}", Convert.ToDouble(reader["HSL"]));
                                        ModuleBHXH.KhoangThoiGian(newRow["TTCHITIET"].ToString(), newRow["DTCHITIET"].ToString(), ref nam, ref thang);
                                    }
                                    else if (reader["PA"].ToString() == "TS")
                                    {
                                        ModuleBHXH.KhoangThoiGian(newRow["TTCHITIET"].ToString(), newRow["DTCHITIET"].ToString(), ref nam, ref thang);
                                    }

                                }
                                dsIntoroi.Tables[0].Rows.Add(newRow);
                            }
                            reader.Close();
                            //TRUONG HOP BHTN
                            queryString = "exec sp_executesql N'SELECT Intr_dtl.KEYSL, Intr_dtl.KEYP, Intr_dtl.MADVI, Intr_dtl.TUTHANG,  Intr_dtl.DENTHANG, "
                           + " Intr_dtl.LOAIDT, Intr_dtl.MA_NTE, Intr_dtl.PA,  Intr_dtl.ML, Intr_dtl.HSL, Intr_dtl.PC1, Intr_dtl.PC2, Intr_dtl.PC3,  "
                           + " Intr_dtl.PC4, Intr_dtl.TYLE_BHXH, Intr_dtl.TYLE_BHTN, Intr_dtl.NOIDUNG,  Intr_dtl.KIEMTRA, Intr_dtl.MA_QUAN, "
                           + " Intr_dtl.USERCODE FROM dbo.INTR_DTL Intr_dtl WHERE Intr_dtl.KEYSL = @P1    "
                           + " AND Intr_dtl.TYLE_BHTN <> 0 order by Intr_dtl.TUTHANG', N'@P1 varchar(22)', '" + FlxDetail.Rows[i]["KEYSL"] + "'";
                            command.CommandText = queryString;
                            reader = command.ExecuteReader();
                            while (reader.Read())
                            {
                                newRow = dsIntoroi.Tables[0].NewRow();
                                newRow["KEYSL"] = FlxDetail.Rows[i]["KEYSL"];
                                newRow["SOBHXH"] = FlxDetail.Rows[i]["SOBHXH"];
                                newRow["HOTEN"] = FlxDetail.Rows[i]["HO"].ToString().Trim() + " " + FlxDetail.Rows[i]["TEN"].ToString().Trim();
                                newRow["TUTHANG"] = ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["TUTHANG"].ToString());
                                newRow["DENTHANG"] = ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["DENTHANG"].ToString());
                                newRow["LOAIXN"] = FlxDetail.Rows[i]["XACNHAN"].ToString();
                                newRow["TTCHITIET"] = ModuleBHXH.FormatThangNam(reader["TUTHANG"].ToString());
                                newRow["DTCHITIET"] = ModuleBHXH.FormatThangNam(reader["DENTHANG"].ToString());
                                newRow["NOIDUNG"] =  reader["NOIDUNG"].ToString().Trim().Substring(0, 1).ToUpper() + reader["NOIDUNG"].ToString().Trim().Substring(1); 
                                if (FlxDetail.Rows[i]["XACNHAN"].ToString() == "QT")
                                {
                                    newRow["TTDT"] = "Tõ Th¸ng " + newRow["TUTHANG"].ToString() + " §Õn Th¸ng " + newRow["DENTHANG"];
                                }
                                else if (FlxDetail.Rows[i]["XACNHAN"].ToString().Trim() == "")
                                {
                                    newRow["TTDT"] = "N¨m : " + FlxDetail.Rows[i]["denthang"].ToString().Substring(0, 4);
                                }
                                else
                                {
                                    newRow["TTDT"] = "N¨m : " + FlxDetail.Rows[i]["denthangxn"].ToString().Substring(0, 4);
                                }
                                //truong hop bao hiem that nghiep
                                if (Convert.ToInt16(reader["TYLE_BHTN"]) != 0)
                                {
                                    newRow["TLBHXH"] = string.Format("{0:##}", reader["TYLE_BHTN"]) + "%";
                                }
                                //pc1
                                if (Convert.ToDouble(reader["PC1"]) > 0)
                                {
                                    newRow["LOAIPC"] = "CV";
                                    newRow["MUCPC"] = String.Format("{0:0.00}", reader["PC1"]);
                                    if (Convert.ToDouble(reader["PC2"]) > 0)
                                    {
                                        newRow["LOAIPC"] = newRow["LOAIPC"] + Environment.NewLine + "TV";
                                        newRow["MUCPC"] = newRow["MUCPC"] + Environment.NewLine + Convert.ToInt16(Convert.ToDouble(reader["PC2"]) * 100 / Convert.ToDouble(reader["HSL"])).ToString() + "%";
                                    }
                                    if (Convert.ToDouble(reader["PC3"]) > 0)
                                    {
                                        newRow["LOAIPC"] = newRow["LOAIPC"] + Environment.NewLine + "TN";
                                        newRow["MUCPC"] = newRow["MUCPC"] + Environment.NewLine +
                                            Convert.ToInt16(Convert.ToDouble(reader["PC3"]) * 100 /
                                            (Convert.ToDouble(reader["HSL"]) + Convert.ToDouble(reader["PC2"]) +
                                            Convert.ToDouble(reader["PC1"]))).ToString() + "%";
                                    }
                                }
                                //pc2
                                else if (Convert.ToDouble(reader["PC2"]) > 0)
                                {
                                    newRow["LOAIPC"] = "TV";
                                    newRow["MUCPC"] = Convert.ToInt16(Convert.ToDouble(reader["PC2"]) * 100 / Convert.ToDouble(reader["HSL"])).ToString() + "%";
                                    if (Convert.ToDouble(reader["PC3"]) > 0)
                                    {
                                        newRow["LOAIPC"] = newRow["LOAIPC"] + Environment.NewLine + "TN";
                                        newRow["MUCPC"] = newRow["MUCPC"] + Environment.NewLine +
                                            Convert.ToInt16(Convert.ToDouble(reader["PC3"]) * 100 /
                                            (Convert.ToDouble(reader["HSL"]) + Convert.ToDouble(reader["PC2"]) +
                                            Convert.ToDouble(reader["PC1"]))).ToString() + "%";
                                    }
                                }
                                //PC3
                                else if (Convert.ToDouble(reader["PC3"]) > 0)
                                {

                                    newRow["LOAIPC"] = "TN";
                                    newRow["MUCPC"] = Convert.ToInt16(Convert.ToDouble(reader["PC3"]) * 100 /
                                        Convert.ToDouble(reader["HSL"])).ToString() + "%";
                                }
                                if (Convert.ToInt32(reader["ML"]) != 0)
                                {
                                    newRow["ML"] = string.Format("{0:###,##.###}", Convert.ToInt32(reader["ML"]));
                                    ModuleBHXH.KhoangThoiGian(newRow["TTCHITIET"].ToString(), newRow["DTCHITIET"].ToString(), ref namtn, ref thangtn);
                                }
                                else if (Convert.ToInt32(reader["HSL"]) != 0)
                                {
                                    newRow["ML"] = string.Format("{0:###,##.000}", Convert.ToDouble(reader["HSL"]));
                                    ModuleBHXH.KhoangThoiGian(newRow["TTCHITIET"].ToString(), newRow["DTCHITIET"].ToString(), ref namtn, ref thangtn);
                                }
                                dsIntoroi.Tables[0].Rows.Add(newRow);
                            }
                            reader.Close();
                            //dieu chinh bhxh
                            DieuChinhBHXH(i, dsIntoroi);
                            //dieu chinh bhtn
                            DieuChinhBHTN(i, dsIntoroi);
                            //tinh tong thoi gian tham gia
                            for (int j = range; j < dsIntoroi.Tables[0].Rows.Count; j++)
                            {
                                oldrow = dsIntoroi.Tables[0].Rows[j];
                                //truong hop bhxh
                                if (nam != 0 || thang != 0)
                                {
                                    oldrow["BHXH"] = "Thêi gian ®ãng BHXH tõ " + ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["TUTHANG"].ToString()) + " ®Õn " + ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["DENTHANG"].ToString()) + " lµ ";
                                    if (nam != 0)
                                    {
                                        oldrow["BHXH"] = oldrow["BHXH"].ToString() + nam + " n¨m ";
                                    }
                                    if (thang != 0)
                                    {
                                        oldrow["BHXH"] = oldrow["BHXH"].ToString() + thang + " th¸ng";

                                    }
                                }
                                //truong hop bhtn
                                if (namtn != 0 || thangtn != 0)
                                {
                                    oldrow["BHXH"] = oldrow["BHXH"] + Environment.NewLine + "Thêi gian ®ãng BHTN tõ " + ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["TUTHANG"].ToString()) + " ®Õn " + ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["DENTHANG"].ToString()) + " lµ ";
                                    if (namtn != 0)
                                    {
                                        oldrow["BHXH"] = oldrow["BHXH"].ToString() + namtn + " n¨m";
                                    }
                                    if (thangtn != 0)
                                    {
                                        oldrow["BHXH"] = oldrow["BHXH"].ToString() + thangtn + " th¸ng";
                                    }
                                }
                                //truong hop BL va HT
                                if (FlxDetail.Rows[i]["xacnhan"].ToString() == "BL" || FlxDetail.Rows[i]["xacnhan"].ToString() == "HT")
                                {
                                    oldrow = dsIntoroi.Tables[0].Rows[j];
                                    //TRuong hop bhxh
                                    if (FlxDetail.Rows[i]["sonam"].ToString() != "0" || FlxDetail.Rows[i]["sothang"].ToString() != "0")
                                    {
                                        oldrow["BHXH"] = oldrow["BHXH"] + Environment.NewLine + "Thêi gian ®ãng BHXH vµo quü h­u trÝ, tö tuÊt ®Õn th¸ng " + ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["denthangxn"].ToString()) + " lµ ";
                                        if (FlxDetail.Rows[i]["sonam"].ToString() != "0")
                                        {
                                            oldrow["BHXH"] = oldrow["BHXH"].ToString() + FlxDetail.Rows[i]["sonam"].ToString() + " n¨m ";
                                        }
                                        if (FlxDetail.Rows[i]["sothang"].ToString() != "0")
                                        {
                                            oldrow["BHXH"] = oldrow["BHXH"].ToString() + FlxDetail.Rows[i]["sothang"].ToString() + " th¸ng";
                                        }
                                    }
                                    //TRuong hop bhtn
                                    if (FlxDetail.Rows[i]["sonamtn"].ToString() != "0" || FlxDetail.Rows[i]["sothangtn"].ToString() != "0")
                                    {
                                        oldrow["BHXH"] = oldrow["BHXH"] + Environment.NewLine + "Thêi gian ®ãng BHTN vµo quü BHTN ®Õn th¸ng " + ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["denthangxntn"].ToString()) + " lµ ";
                                        if (FlxDetail.Rows[i]["sonamtn"].ToString() != "0")
                                        {
                                            oldrow["BHXH"] = oldrow["BHXH"].ToString() + FlxDetail.Rows[i]["sonamtn"].ToString() + " n¨m ";
                                        }
                                        if (FlxDetail.Rows[i]["sothangtn"].ToString() != "0")
                                        {
                                            oldrow["BHXH"] = oldrow["BHXH"].ToString() + FlxDetail.Rows[i]["sothangtn"].ToString() + " th¸ng";
                                        }
                                    }
                                }

                            }

                        }//ket thuc ham if kiem tra check
                    }
                   
                }
                //chuyen sang font unicode
                for(int i = 0;i<dsIntoroi.TBINTOROI.Rows.Count;i++)
                {
                    dsIntoroi.TBINTOROI.Rows[i]["NOIDUNG"] = Converter.TCVN3ToUnicode(dsIntoroi.TBINTOROI.Rows[i]["NOIDUNG"].ToString());
                }

                Report f = new Report();
                ReportDocument cr = new ReportDocument();
                cr.Load("crpintoroi.rpt");
                cr.SetDataSource(dsIntoroi);

                foreach (CrystalDecisions.CrystalReports.Engine.FormulaFieldDefinition thisFormulaField in cr.DataDefinition.FormulaFields)
                {
                    if (thisFormulaField.Name == "User")
                    {
                        thisFormulaField.Text = "'" + BHXH_NT.ModuleBHXH.strUser + "'";
                    }
                }
                f.crpView.ReportSource = cr;
                f.Show();
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0} Second exception caught.", ex);
            }
            Cursor.Current = Cursors.Default;
        }
        /// <summary>
        /// in qua trinh so bhxh
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn07SBH_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            QuatrinhBHXH dsQuatrinh = new QuatrinhBHXH();
            QuatrinhBHXH dsQuatrinh1 = new QuatrinhBHXH();//dataset trung gian
            DataRow newRow = null;
            DataRow oldRow = null;
            DataRow currentRow = null;
            SqlCommand command;
            SqlDataReader reader;
            int i, j, range;
            dsIntoroi.Clear();
            //int nam = 0, thang = 0;
            string sobhxh = "", Maxqt = "", queryString;
            //try
            //{
            for (int k = 1; k < FlxDetail.Rows.Count; k++)
            {
                //chi xet truong hop GIAM
                if ((FlxDetail.Rows[k]["xacnhan"].ToString() == "BL"
                    || FlxDetail.Rows[k]["xacnhan"].ToString() == "HT"
                    || FlxDetail.Rows[k]["xacnhan"].ToString() == "TU")
                    && Convert.ToInt16(FlxDetail.Rows[k]["CHECK"]) == 1)
                {
                    range = dsIntoroi.Tables[1].Rows.Count;//Dung update tong ket so  bhxh
                    sobhxh = FlxDetail.Rows[k]["SoBHXH"].ToString();
                    Maxqt = FlxDetail.Rows[k]["DenThang"].ToString();
                    queryString = "exec sp_executesql N'EXEC QUATRINHCN @P1 , @P2 , @P3 ', "
                        + " N'@P1 varchar(16),@P2 varchar(6),@P3 varchar(6)', '" + sobhxh + "', '190101', '" + Maxqt + "'";
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        command = connection.CreateCommand();
                        command.CommandText = queryString;
                        connection.Open();
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            newRow = dsQuatrinh1.Tables[0].NewRow();
                            newRow["Madvi"] = reader["Madvi"];
                            newRow["Maqt"] = reader["Maqt"].ToString().Substring(0, 6);
                            newRow["Tuthang"] = reader["Tuthang"];
                            newRow["Denthang"] = reader["Denthang"];
                            newRow["Loaidt"] = reader["Loaidt"];
                            newRow["Ma_nte"] = reader["Ma_nte"];
                            newRow["Mucluong"] = reader["ML"];
                            newRow["Hsl"] = reader["Hsl"];
                            newRow["PCCV"] = reader["pc1"];
                            newRow["PCTN"] = reader["pc2"];
                            newRow["PCNG"] = reader["pc3"];
                            //Tu thang 12/2007 khong co pc4
                            newRow["PCKV"] = 0;
                            newRow["pa"] = reader["pa"];
                            newRow["loaips"] = reader["loaips"];
                            newRow["Congviec"] = reader["Congviec"];
                            //truong hop SB
                            if (newRow["pa"].ToString() == "SB")
                            {
                                PA_SB(dsQuatrinh1, newRow);
                            }
                            else
                            {
                                dsQuatrinh1.Tables[0].Rows.Add(newRow);
                            }


                        }
                    }
                    reader.Close();
                    //CAC TRUONG HOP KHAC
                    for (i = 0; i < dsQuatrinh1.Tables[0].Rows.Count; i++)
                    {
                        currentRow = dsQuatrinh1.Tables[0].Rows[i];
                        newRow = dsQuatrinh.Tables[0].NewRow();
                        if (currentRow["loaips"].ToString() == "1") //truong hop ps = 1
                        {

                            newRow["Madvi"] = currentRow["Madvi"];
                            newRow["Tuthang"] = currentRow["Maqt"];
                            newRow["Loaidt"] = currentRow["Loaidt"];
                            newRow["Ma_nte"] = currentRow["Ma_nte"];
                            newRow["Mucluong"] = currentRow["Mucluong"];
                            newRow["Hsl"] = currentRow["Hsl"];
                            newRow["PCCV"] = currentRow["PCCV"];
                            newRow["PCTN"] = currentRow["PCTN"];
                            newRow["PCNG"] = currentRow["PCNG"];
                            //Tu thang 12/2007 khong co pc4
                            newRow["PCKV"] = 0;
                            newRow["pa"] = currentRow["pa"];
                            newRow["loaips"] = currentRow["loaips"];

                            if (currentRow["Congviec"].ToString().Trim() == "")
                            {
                                newRow["Congviec"] = FlxDetail.Rows[k]["MACV"];
                            }
                            else
                            {
                                newRow["Congviec"] = currentRow["Congviec"];
                            }
                            //sap xep theo maqt
                            for (j = 0; j < dsQuatrinh.Tables[0].Rows.Count; j++)
                            {
                                currentRow = dsQuatrinh.Tables[0].Rows[j];
                                if (Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["Tuthang"]))
                                {

                                    insertNewRow(dsQuatrinh, newRow, Convert.ToInt32(currentRow["Tuthang"]), j);
                                    break;
                                }
                                else if (Convert.ToInt32(newRow["Tuthang"]) == Convert.ToInt32(currentRow["Tuthang"]))
                                {
                                    newRow["Denthang"] = currentRow["Denthang"];
                                    newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                    Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                                    dsQuatrinh.Tables[0].Rows.InsertAt(newRow, j);
                                    dsQuatrinh.Tables[0].Rows.RemoveAt(j + 1);
                                    break;
                                }
                                else if (Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["Tuthang"])
                                    && Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["Denthang"]))
                                {
                                    newRow["Denthang"] = currentRow["Denthang"];
                                    UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                                    newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                    Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                                    dsQuatrinh.Tables[0].Rows.InsertAt(newRow, j + 1);
                                    break;
                                }
                                else if (Convert.ToInt32(newRow["Tuthang"]) == Convert.ToInt32(currentRow["Denthang"]))
                                {
                                    UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                                    newRow["Denthang"] = newRow["Tuthang"];
                                    newRow["Sothang"] = 0;
                                    dsQuatrinh.Tables[0].Rows.InsertAt(newRow, j + 1);
                                    break;
                                }

                            }
                            if (dsQuatrinh.Tables[0].Rows.Count == 0)
                            {
                                newRow["denthang"] = Maxqt;
                                newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                    Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                                dsQuatrinh.Tables[0].Rows.Add(newRow);
                            }
                            else if (dsQuatrinh.Tables[0].Rows.Count == j)
                            {
                                dsQuatrinh.Tables[0].Rows[j - 1]["Denthang"] = Convert.ToInt32(newRow["Tuthang"]) - 1;
                                if (dsQuatrinh.Tables[0].Rows[j - 1]["Denthang"].ToString().Substring(4) == "00")
                                {
                                    dsQuatrinh.Tables[0].Rows[j - 1]["Denthang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[j - 1]["Denthang"].ToString().Substring(0, 4)) - 1;
                                    dsQuatrinh.Tables[0].Rows[j - 1]["Denthang"] = dsQuatrinh.Tables[0].Rows[j - 1]["Denthang"].ToString() + "12";
                                }
                                dsQuatrinh.Tables[0].Rows[j - 1]["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[j - 1]["Tuthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[j - 1]["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                    Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[j - 1]["Denthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[j - 1]["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                                if (Convert.ToInt32(newRow["tuthang"]) <= Convert.ToInt32(Maxqt))
                                {
                                    newRow["Denthang"] = Maxqt;
                                    newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                    Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                                    dsQuatrinh.Tables[0].Rows.Add(newRow);
                                }
                            }
                        }
                        else if (currentRow["loaips"].ToString() == "2")  //loai ps=2
                        {
                            newRow["Madvi"] = currentRow["Madvi"];
                            newRow["Tuthang"] = currentRow["Tuthang"];
                            newRow["Denthang"] = currentRow["Denthang"];
                            newRow["Loaidt"] = currentRow["Loaidt"];
                            newRow["Ma_nte"] = currentRow["Ma_nte"];
                            newRow["Mucluong"] = currentRow["Mucluong"];
                            newRow["Hsl"] = currentRow["Hsl"];
                            newRow["PCCV"] = currentRow["PCCV"];
                            newRow["PCTN"] = currentRow["PCTN"];
                            newRow["PCNG"] = currentRow["PCNG"];
                            newRow["PCKV"] = currentRow["PCKV"];
                            newRow["loaips"] = currentRow["loaips"];

                            newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                    Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                            newRow["pa"] = currentRow["pa"];
                            newRow["Congviec"] = currentRow["Congviec"];
                            //sap xep theo ma qua trinh
                            switch (newRow["pa"].ToString().Trim())
                            {

                                case "AD":
                                    PA_AD(dsQuatrinh, newRow);
                                    break;
                                case "TS":
                                    PA_DC(dsQuatrinh, newRow);
                                    break;
                                case "CD":
                                    PA_CD(dsQuatrinh, newRow);
                                    break;
                                case "":
                                case "DC":
                                case "TM":
                                case "TC":
                                case "TD":
                                case "ON":
                                case "GC":
                                case "GD":
                                case "GH":
                                case "OF":
                                    PA_DC(dsQuatrinh, newRow);
                                    break;

                            }
                            if (newRow["Congviec"].ToString().Trim() == "")
                            {
                                newRow["Congviec"] = FlxDetail.Rows[k]["MACV"];
                            }

                        }
                    }
                    // test(dsQuatrinh);
                    //chen them donvi cho cac dong ko co ten don vi
                    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
                    {
                        oldRow = dsQuatrinh.Tables[0].Rows[i];
                        //tim dong de insert tendenvi
                        if (oldRow["Madvi"].ToString().Trim() == FlxDetail.Rows[k]["Madvi"].ToString().Trim() && oldRow["PA"].ToString() != "TS" && oldRow["PA"].ToString() != "OF" && oldRow["PA"].ToString() != "GH")
                        {
                            oldRow["Tendvi"] = FlxDetail.Rows[k]["TENDVI"];
                            oldRow["DiaChi"] = FlxDetail.Rows[k]["DIACHI"];
                        }
                        else if (oldRow["Madvi"].ToString() != "HA0000A" && oldRow["PA"].ToString() != "TS" && oldRow["PA"].ToString() != "OF" && oldRow["PA"].ToString() != "GH")
                        {
                            using (SqlConnection connection = new SqlConnection(connectionString))
                            {
                                connection.Open();
                                command = connection.CreateCommand();
                                queryString = "select Tendvi,DiaChi from DMDONVI WHERE MADVI = '" + oldRow["Madvi"].ToString() + "'";
                                command = connection.CreateCommand();
                                command.CommandText = queryString;
                                reader = command.ExecuteReader();
                                reader.Read();
                                oldRow["Tendvi"] = reader["Tendvi"];
                                oldRow["DiaChi"] = reader["DiaChi"];
                                reader.Close();
                            }
                        }
                        else if (oldRow["PA"].ToString() == "TS")
                        {
                            oldRow["Congviec"] = "";
                            oldRow["Tendvi"] = "NghØ h­ëng chÕ ®é thai s¶n";
                            oldRow["Mucluong"] = 0;
                            oldRow["Hsl"] = 0;

                        }
                        else if (oldRow["PA"].ToString() == "OF" || oldRow["PA"].ToString() == "GH")
                        {
                            oldRow["Congviec"] = "";
                            oldRow["Tendvi"] = "Kh«ng tham gia";
                            oldRow["Mucluong"] = 0;
                            oldRow["Hsl"] = 0;
                        }

                    }
                    //chen them donvi cho cac dong ko co ten don vi nam trong bang history
                    queryString = "exec sp_executesql N'SELECT Madvi, Tendvi, Nghenghiep, Loaidt, Tuthang, Denthang, Dk1, Dk2, Dk3, Dk4, Dk5, Dk6 "
                    + " FROM HISTORY WHERE Sobhxh=@P1  AND ((@P2  BETWEEN Tuthang AND Denthang) or "
                    + " (@P3  BETWEEN Tuthang AND Denthang) OR (@P4 <=Tuthang AND @P5 >=Denthang)) ',"
                    + " N'@P1 varchar(10),@P2 varchar(6),@P3 varchar(6),@P4 varchar(6),@P5 varchar(6)', '" + sobhxh + "', '196001', '" + Maxqt + "'"
                    + " ,'196001', '" + Maxqt + "'";
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        command = connection.CreateCommand();
                        command.CommandText = queryString;
                        connection.Open();
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
                            {
                                oldRow = dsQuatrinh.Tables[0].Rows[i];
                                //tim dong de insert tendenvi
                                if (oldRow["loaips"].ToString() == "2" &&
                                    oldRow["DenThang"].ToString() == reader["Denthang"].ToString() &&
                                    oldRow["PA"].ToString() != "TS" &&
                                    oldRow["PA"].ToString() != "OF" && oldRow["PA"].ToString() != "GH")
                                {
                                    oldRow["Tendvi"] = reader["Tendvi"];
                                    oldRow["DiaChi"] = "";
                                }
                                else if (oldRow["PA"].ToString() == "TS")
                                {
                                    oldRow["Congviec"] = "";
                                    oldRow["Tendvi"] = "NghØ h­ëng chÕ ®é thai s¶n";
                                    oldRow["Mucluong"] = 0;
                                    oldRow["Hsl"] = 0;
                                }
                                else if (oldRow["PA"].ToString() == "OF" || oldRow["PA"].ToString() == "GH")
                                {
                                    oldRow["Congviec"] = "";
                                    oldRow["Tendvi"] = "Kh«ng tham gia";
                                    oldRow["Mucluong"] = 0;
                                    oldRow["Hsl"] = 0;
                                }
                            }
                        }
                        reader.Close();
                    }
                    //them dong de hoan thanh qua trinh
                    oldRow = null;
                    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
                    {

                        if (dsQuatrinh.Tables[0].Rows[i]["loaips"].ToString() == "1")
                        {
                            oldRow = dsQuatrinh.Tables[0].Rows[i];
                        }

                        if (oldRow != null && DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString().Substring(4, 2) + "/01")) > 1 && dsQuatrinh.Tables[0].Rows[i]["pa"].ToString().Trim() != "")
                        {
                            newRow = dsQuatrinh.Tables[0].NewRow();
                            newRow["Madvi"] = oldRow["Madvi"];
                            newRow["Tuthang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["denThang"]) + 1;
                            if (newRow["Tuthang"].ToString().Substring(4) == "13")
                            {
                                newRow["Tuthang"] = Convert.ToInt32(newRow["Tuthang"].ToString().Substring(0, 4)) + 1;
                                newRow["Tuthang"] = newRow["Tuthang"].ToString() + "01";
                            }
                            newRow["DenThang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString()) - 1;
                            if (newRow["DenThang"].ToString().Substring(4) == "00")
                            {
                                newRow["DenThang"] = Convert.ToInt32(newRow["DenThang"].ToString().Substring(0, 4)) - 1;
                                newRow["DenThang"] = newRow["DenThang"].ToString() + "12";
                            }
                            newRow["Loaidt"] = oldRow["Loaidt"];
                            newRow["Ma_nte"] = oldRow["Ma_nte"];
                            newRow["Mucluong"] = oldRow["Mucluong"];
                            newRow["Hsl"] = oldRow["Hsl"];
                            newRow["PCCV"] = oldRow["PCCV"];
                            newRow["PCTN"] = oldRow["PCTN"];
                            newRow["PCNG"] = oldRow["PCNG"];
                            newRow["PCKV"] = oldRow["PCKV"];
                            newRow["pa"] = oldRow["pa"];
                            newRow["Congviec"] = oldRow["Congviec"];
                            newRow["Tendvi"] = oldRow["Tendvi"];
                            newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                              Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                            i++;


                        }
                    }
                    //merge
                    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
                    {
                        oldRow = dsQuatrinh.Tables[0].Rows[i];
                        newRow = dsQuatrinh.Tables[0].Rows[i + 1];
                        if (oldRow["Denthang"] is System.DBNull) { break; }
                        if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) == 1)
                        {

                            if (oldRow["Mucluong"].ToString() == newRow["Mucluong"].ToString() &&
                                oldRow["HSL"].ToString() == newRow["HSL"].ToString() &&
                                 oldRow["PCCV"].ToString() == newRow["PCCV"].ToString() &&
                                 oldRow["PCTN"].ToString() == newRow["PCTN"].ToString() &&
                                 oldRow["PCNG"].ToString() == newRow["PCNG"].ToString() &&
                                 oldRow["PCKV"].ToString() == newRow["PCKV"].ToString() &&
                                 oldRow["PCCV"].ToString() == newRow["PCCV"].ToString() &&
                                //oldRow["Pa"].ToString() == newRow["Pa"].ToString() &&
                                 oldRow["Congviec"].ToString().ToUpper().Trim() == newRow["Congviec"].ToString().ToUpper().Trim() &&
                                 oldRow["Tendvi"].ToString() == newRow["Tendvi"].ToString())
                            {
                                newRow["Tuthang"] = oldRow["Tuthang"];
                                newRow["Sothang"] = Convert.ToInt32(newRow["Sothang"]) + Convert.ToInt32(oldRow["Sothang"]);
                                oldRow.Delete();
                                i = i - 1;
                            }
                        }
                        //Xoa dong trung
                        else if (Convert.ToInt32(oldRow["tuThang"]) >= Convert.ToInt32(newRow["tuThang"]) && Convert.ToInt32(oldRow["denThang"]) <= Convert.ToInt32(newRow["denThang"]))
                        {
                            oldRow.Delete();
                            i = i - 1;
                        }
                    }
                    //cat theo ti le bhxh
                    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
                    {
                        oldRow = dsQuatrinh.Tables[0].Rows[i];
                        if (oldRow["Denthang"] is System.DBNull) { break; }
                        if (Convert.ToInt32(oldRow["denThang"].ToString()) > 199412 && Convert.ToInt32(oldRow["tuThang"].ToString()) <= 199412 && oldRow["pa"].ToString() != "GH" && oldRow["pa"].ToString() != "TS" && oldRow["pa"].ToString() != "OF")
                        {

                            newRow = dsQuatrinh.Tables[0].NewRow();
                            newRow["Madvi"] = oldRow["Madvi"];
                            newRow["Tuthang"] = oldRow["Tuthang"];
                            newRow["Denthang"] = oldRow["Denthang"];
                            newRow["Loaidt"] = oldRow["Loaidt"];
                            newRow["Ma_nte"] = oldRow["Ma_nte"];
                            newRow["Mucluong"] = oldRow["Mucluong"];
                            newRow["Hsl"] = oldRow["Hsl"];
                            newRow["PCCV"] = oldRow["PCCV"];
                            newRow["PCTN"] = oldRow["PCTN"];
                            newRow["PCNG"] = oldRow["PCNG"];
                            newRow["PCKV"] = oldRow["PCKV"];
                            newRow["pa"] = oldRow["pa"];
                            newRow["Congviec"] = oldRow["Congviec"];
                            newRow["Tendvi"] = oldRow["Tendvi"];
                            newRow["Diachi"] = oldRow["Diachi"];
                            oldRow["denthang"] = "199412";
                            oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                  Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                            newRow["tuThang"] = "199501";
                            newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                  Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);

                        }
                        else if (Convert.ToInt32(oldRow["denThang"].ToString()) > 200912 && Convert.ToInt32(oldRow["tuThang"].ToString()) <= 200912 && oldRow["pa"].ToString() != "GH" && oldRow["pa"].ToString() != "TS" && oldRow["pa"].ToString() != "OF")
                        {

                            newRow = dsQuatrinh.Tables[0].NewRow();
                            newRow["Madvi"] = oldRow["Madvi"];
                            newRow["Tuthang"] = oldRow["Tuthang"];
                            newRow["Denthang"] = oldRow["Denthang"];
                            newRow["Loaidt"] = oldRow["Loaidt"];
                            newRow["Ma_nte"] = oldRow["Ma_nte"];
                            newRow["Mucluong"] = oldRow["Mucluong"];
                            newRow["Hsl"] = oldRow["Hsl"];
                            newRow["PCCV"] = oldRow["PCCV"];
                            newRow["PCTN"] = oldRow["PCTN"];
                            newRow["PCNG"] = oldRow["PCNG"];
                            newRow["PCKV"] = oldRow["PCKV"];
                            newRow["pa"] = oldRow["pa"];
                            newRow["Congviec"] = oldRow["Congviec"];
                            newRow["Tendvi"] = oldRow["Tendvi"];
                            newRow["Diachi"] = oldRow["Diachi"];
                            oldRow["denthang"] = "200912";
                            oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                  Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                            newRow["tuThang"] = "201001";
                            newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                  Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                            break;
                        }
                    }
                    //them dong khong tham gia và cắt các dòng có thời gian trung nhau
                    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
                    {
                        oldRow = dsQuatrinh.Tables[0].Rows[i];
                        newRow = dsQuatrinh.Tables[0].Rows[i + 1];
                        //cat cac dong co thoi gian trung
                        if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) <= 0)
                        {
                            oldRow["Denthang"] = Convert.ToInt32(newRow["Tuthang"]) - 1;
                            if (oldRow["DenThang"].ToString().Substring(4) == "00")
                            {
                                oldRow["DenThang"] = Convert.ToInt32(oldRow["DenThang"].ToString().Substring(0, 4)) - 1;
                                oldRow["DenThang"] = oldRow["DenThang"].ToString() + "12";
                            }
                            oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                 Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                        }
                        //them dong ko tham gia
                        else if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) > 1)
                        {
                            DataRow ktgRow = dsQuatrinh.Tables[0].NewRow();
                            //newRow["Madvi"] = oldRow["Madvi"];
                            ktgRow["Tuthang"] = Convert.ToInt32(oldRow["denThang"]) + 1;
                            if (ktgRow["Tuthang"].ToString().Substring(4) == "13")
                            {
                                ktgRow["Tuthang"] = Convert.ToInt32(ktgRow["Tuthang"].ToString().Substring(0, 4)) + 1;
                                ktgRow["Tuthang"] = ktgRow["Tuthang"].ToString() + "01";
                            }
                            ktgRow["DenThang"] = Convert.ToInt32(newRow["Tuthang"].ToString()) - 1;

                            if (ktgRow["DenThang"].ToString().Substring(4) == "00")
                            {
                                ktgRow["DenThang"] = Convert.ToInt32(ktgRow["DenThang"].ToString().Substring(0, 4)) - 1;
                                ktgRow["DenThang"] = ktgRow["DenThang"].ToString() + "12";
                            }
                            ktgRow["Mucluong"] = 0;
                            ktgRow["Hsl"] = 0;
                            ktgRow["PCCV"] = 0;
                            ktgRow["PCTN"] = 0;
                            ktgRow["PCNG"] = 0;
                            ktgRow["PCKV"] = 0;

                            ktgRow["pa"] = "OF";
                            ktgRow["Tendvi"] = "Kh«ng tham gia";
                            ktgRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(ktgRow["Tuthang"].ToString().Substring(0, 4) + "/" + ktgRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                              Convert.ToDateTime(ktgRow["Denthang"].ToString().Substring(0, 4) + "/" + ktgRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                            dsQuatrinh.Tables[0].Rows.InsertAt(ktgRow, i + 1);


                        }
                    }
                    //dua va dataset Intoroi
                    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
                    {
                        newRow = dsIntoroi.Tables[1].NewRow();
                        newRow["KEYSL"] = FlxDetail.Rows[k]["KEYSL"];
                        newRow["SOBHXH"] = FlxDetail.Rows[k]["SOBHXH"];
                        newRow["HOTEN"] = FlxDetail.Rows[k]["HO"].ToString().Trim() + " " + FlxDetail.Rows[k]["TEN"].ToString();
                        newRow["LOAIXN"] = FlxDetail.Rows[k]["XACNHAN"].ToString();
                        newRow["TTCHITIET"] = ModuleBHXH.FormatThangNam(dsQuatrinh.Tables[0].Rows[i]["TUTHANG"].ToString());
                        newRow["DTCHITIET"] = ModuleBHXH.FormatThangNam(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"].ToString());
                        if (dsQuatrinh.Tables[0].Rows[i]["Congviec"].ToString().Trim() == "")
                        {
                            newRow["NOIDUNG"] = dsQuatrinh.Tables[0].Rows[i]["Tendvi"].ToString().Trim() + ". " + dsQuatrinh.Tables[0].Rows[i]["DiaChi"].ToString().Trim();
                        }
                        else
                        {
                            newRow["NOIDUNG"] = dsQuatrinh.Tables[0].Rows[i]["Congviec"].ToString().Trim() + ". " + dsQuatrinh.Tables[0].Rows[i]["Tendvi"].ToString().Trim()
                                + ". " + dsQuatrinh.Tables[0].Rows[i]["DiaChi"].ToString().Trim();
                        }


                        if (dsQuatrinh.Tables[0].Rows[i]["PA"].ToString() != "TS" && dsQuatrinh.Tables[0].Rows[i]["PA"].ToString() != "OF" && dsQuatrinh.Tables[0].Rows[i]["PA"].ToString() != "GH")
                        {
                            if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"]) <= 199412)
                            {
                                newRow["TLBHXH"] = "";
                            }
                            else if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"]) <= 200912)
                            {
                                newRow["TLBHXH"] = string.Format("{0:##}", 20) + "%";
                            }
                            else
                            {
                                newRow["TLBHXH"] = string.Format("{0:##}", 22) + "%";
                            }
                        }
                        if (Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCCV"]) > 0)
                        {
                            newRow["MUCPC"] = String.Format("{0:###,#0.000}", dsQuatrinh.Tables[0].Rows[i]["PCCV"]);
                        }
                        if (Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCTN"]) > 0)
                        {
                            newRow["LOAIPC"] = Convert.ToInt16(Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCTN"]) * 100 / Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["HSL"])).ToString() + "%";
                        }
                        if (Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCNG"]) > 0)
                        {
                            newRow["TNNGHE"] = Convert.ToInt16(Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCNG"]) * 100 /
                                (Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["HSL"]) +
                                Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCTN"]) +
                                Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCCV"]))).ToString() + "%";
                        }
                        if (Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCKV"]) > 0)
                        {
                            newRow["KHAC"] = String.Format("{0:###,#0.000}", dsQuatrinh.Tables[0].Rows[i]["PCKV"]);
                        }

                        newRow["GIOITINH"] = FlxDetail.Rows[k]["GIOITINH"];
                        newRow["NGAYSINH"] = FlxDetail.Rows[k]["NGAYSINH"];
                        newRow["SOCMND"] = FlxDetail.Rows[k]["SOCMND"];
                        newRow["NGAYCMND"] = FlxDetail.Rows[k]["NGAYCMND"];
                        newRow["NOICAP"] = FlxDetail.Rows[k]["NOICAP"];
                        newRow["DIACHI"] = FlxDetail.Rows[k]["DIACHI"];
                        // newRow["MACV"] = FlxDetail.Rows[k]["MACV"];
                        newRow["DANTOC"] = FlxDetail.Rows[k]["DANTOC"];
                        newRow["NOIKHAI"] = FlxDetail.Rows[k]["NOIKHAI"];
                        newRow["QUOCTICH"] = FlxDetail.Rows[k]["QUOCTICH"];


                        if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["MUCLUONG"]) != 0)
                        {
                            if (dsQuatrinh.Tables[0].Rows[i]["Ma_nte"].ToString() == "VND")
                            {
                                newRow["ML"] = string.Format("{0:###,##.###}", Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["MUCLUONG"]));
                            }
                            else
                            {
                                newRow["ML"] = string.Format("{0:###,##.00}", Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["MUCLUONG"]));
                                newRow["NOIDUNG"] = newRow["NOIDUNG"] + " - §ãNG B»NG " + dsQuatrinh.Tables[0].Rows[i]["Ma_nte"].ToString();
                            }

                        }
                        else if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["HSL"]) != 0)
                        {
                            newRow["ML"] = string.Format("{0:###,##.000}", Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["HSL"]));
                        }
                        dsIntoroi.Tables[1].Rows.Add(newRow);
                    }

                    dsQuatrinh.Tables[0].Rows.Clear();
                    dsQuatrinh1.Tables[0].Rows.Clear();
                    Bhtn(dsIntoroi, k);

                    for (j = range; j < dsIntoroi.Tables[1].Rows.Count; j++)
                    {
                        newRow = dsIntoroi.Tables[1].Rows[j];
                        if (FlxDetail.Rows[k]["sonam"].ToString() != "0" || FlxDetail.Rows[k]["sothang"].ToString() != "0")
                        {
                            newRow["BHXH"] = "Thêi gian ®ãng BHXH vµo quü h­u trÝ, tö tuÊt ®Õn th¸ng "
                                + ModuleBHXH.FormatThangNam(FlxDetail.Rows[k]["denthangxn"].ToString()).Substring(0, 2) + " n¨m "
                                + ModuleBHXH.FormatThangNam(FlxDetail.Rows[k]["denthangxn"].ToString()).Substring(3) + " lµ ";
                            if (FlxDetail.Rows[k]["sonam"].ToString() != "0")
                            {
                                newRow["BHXH"] = newRow["BHXH"].ToString() + FlxDetail.Rows[k]["sonam"].ToString() + " n¨m ";
                            }
                            if (FlxDetail.Rows[k]["sothang"].ToString() != "0")
                            {
                                newRow["BHXH"] = newRow["BHXH"].ToString() + FlxDetail.Rows[k]["sothang"].ToString() + " th¸ng";
                            }
                        }
                        if (FlxDetail.Rows[k]["sonamtn"].ToString() != "0" || FlxDetail.Rows[k]["sothangtn"].ToString() != "0")
                        {
                            newRow["BHXH"] = newRow["BHXH"] + Environment.NewLine + "Thêi gian ®ãng BHTN vµo quü BHTN ®Õn th¸ng "
                                + ModuleBHXH.FormatThangNam(FlxDetail.Rows[k]["denthangxntn"].ToString()).Substring(0, 2) + " n¨m "
                                + ModuleBHXH.FormatThangNam(FlxDetail.Rows[k]["denthangxntn"].ToString()).Substring(3) + " lµ ";
                            if (FlxDetail.Rows[k]["sonamtn"].ToString() != "0")
                            {
                                newRow["BHXH"] = newRow["BHXH"].ToString() + FlxDetail.Rows[k]["sonamtn"].ToString() + " n¨m ";
                            }
                            if (FlxDetail.Rows[k]["sothangtn"].ToString() != "0")
                            {
                                newRow["BHXH"] = newRow["BHXH"].ToString() + FlxDetail.Rows[k]["sothangtn"].ToString() + " th¸ng";
                            }
                        }

                    }

                }

            }
            for(i =0;i<dsIntoroi.Tables[1].Rows.Count;i++)
            {
                dsIntoroi.Tables[1].Rows[i]["NOIDUNG"] = Converter.TCVN3ToUnicode(dsIntoroi.Tables[1].Rows[i]["NOIDUNG"].ToString()).ToUpper();
            }
            Report f = new Report();
            ReportDocument cr = new ReportDocument();
            cr.Load("crp07sbh.rpt");
            cr.SetDataSource(dsIntoroi);
            f.crpView.ReportSource = cr;
            f.Show();
            Cursor.Current = Cursors.Default;
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine("{0} Second exception caught.", ex);
            //}

        }
        /// <summary>
        /// hien thi danh sach cac so bhxh chua cap to roi bao luu
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTaosolieu_Click(object sender, EventArgs e)
        {
            int i=1;
            string queryString;
            Cursor.Current = Cursors.WaitCursor;
            queryString = "SELECT a.Sobhxh,c.Ho, c.Ten, b.Madvi,c.macv,d.diachi,d.tendvi "
            + " FROM HSC47_DTL b LEFT JOIN HOSOCN c ON b.Sobhxh=c.Sobhxh"
            + " inner join MISBHXH_NT.dbo.DMDONVI d on b.Madvi = d.Madvi,"
            + " (SELECT Sobhxh, MAX(Maqt) AS Maqt FROM HSC47_DTL WHERE LEFT(Maqt,6)=Denthang "
            + " AND LEFT(Maqt,6)<='" + ModuleBHXH.GetMonth() + "'  AND LEFT(Maqt,6)>='" + txtNamGiam.Text.Trim() + "01' "
            + " AND CHARINDEX(Pa,'TT/TU/TN/GN/DN/CD/TS/GD/OF')=0 AND CHARINDEX('TA',sobhxh) = 0  GROUP BY Sobhxh) a "
            + " WHERE a.Sobhxh=b.Sobhxh AND a.Maqt=b.Maqt AND LEFT(b.Maqt,6)=b.Denthang  "
            + " AND b.Hsl+b.Pc1+b.Pc2+b.Pc3+b.Pc4+b.Pc5+b.Ml+b.Mlyt=0 AND CHARINDEX(b.Pa,'TT/TU/TN/GN/DN/CD/TS/GD/OF')=0 "
            + " AND CHARINDEX('TA',b.sobhxh) = 0 AND LEFT(b.Maqt,6)<='" + ModuleBHXH.GetMonth() + "' AND LEFT(b.Maqt,6)>='" + txtNamGiam.Text.Trim() + "01' "
            + " and a.sobhxh not in (select sobhxh from MISBHXH_SOTHE_NT.dbo.INTR_HDR where sobhxh = a.sobhxh and "
            + " loaixn in ('BL','TU','HT') and ngaycap >= '01/01/" + txtNamGiam.Text.Trim() + "') ";

            FlxSobhxh.Rows.Count = 1;
            FlxDetail.Rows.Count = 1;
            faQuaTrinh.Rows.Count = 1;
            intSochay = 0;
            using (SqlConnection connection =
                  new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = queryString;
                command.CommandTimeout = 3600;
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    FlxSobhxh.Rows.Count = FlxSobhxh.Rows.Count + 1;
                    FlxSobhxh.Rows[i]["Madvi"] = reader["Madvi"];
                    FlxSobhxh.Rows[i]["Tendvi"] = reader["Tendvi"];
                    FlxSobhxh.Rows[i]["Sobhxh"] = reader["Sobhxh"];
                    FlxSobhxh.Rows[i]["Sobhxh1"] = reader["Sobhxh"].ToString().Trim().Substring(6);
                    FlxSobhxh.Rows[i]["Ho"] = reader["Ho"];
                    FlxSobhxh.Rows[i]["Ten"] = reader["Ten"];
                    FlxSobhxh.Rows[i]["macv"] = reader["macv"];
                    FlxSobhxh.Rows[i]["Diachi"] = reader["Diachi"];
                    FlxSobhxh.Rows[i]["Tuthang"] = "200901";
                    FlxSobhxh.Rows[i]["Xacnhan"] = "BL";
                    i++;

                }
                reader.Close();
            }
            Cursor.Current = Cursors.Default;
        }
        /// <summary>
        /// tinh toan de tao to roi tu nam 2009 toi nay
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnkiemtra_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            QuatrinhBHXH dsQuatrinh = new QuatrinhBHXH(); //chua qua trinh cung tu so bhxh
            QuatrinhBHXH dsTQuatrinh = new QuatrinhBHXH(); // qua trinh trung gian
            int nam=0,thang=0;
            Boolean flagdulieu = false;
            FlxSobhxh.Sort(SortFlags.Ascending, 9);
            FlxSobhxh.Sort(SortFlags.Descending, 1);
            flageFlex = 0;
            dsKQuatrinh.Clear();
            faQuaTrinh.Rows.Count = 1;
           
            string sobhxh = "", Maxqt = "",Maxqt1 = "", thangbd = "", 
                thangkt = "", thangbdMin = "", thanggh,xacnhan,tuthangxn;
            FlxDetail.Rows.Count = 1;
            for (int k = 1; k < FlxSobhxh.Rows.Count; k++) //duyet theo tung so bhxh
            {
                if (Convert.ToInt16(FlxSobhxh.Rows[k]["CHECK"]) == 1)
                {
                    dsTQuatrinh.Tables[0].Rows.Clear();//clear qua trinh
                    dsQuatrinh.Tables[0].Rows.Clear();//clear qua trinh
                    thangbd = "";
                    Maxqt1 = "";
                    //tim thang nho nhat cua qua trinh
                    thangbdMin = (Convert.ToInt32(ModuleBHXH.GetMonth().Substring(0,4)) + 1).ToString() + "01";

                    sobhxh = FlxSobhxh.Rows[k]["SoBHXH"].ToString();

                    bool flag = false;// phan biet in to roi hang nam co chot so ko
                    if (sender == null)//in to roi hang nam
                    {
                        //lay thang cuoi cung
                        flag = GetThangHangNam(k, sobhxh, ref Maxqt1, ref  Maxqt);
                    }
                    else
                    {
                        //lay thang giam
                        if (GetThangChotSo(k, sobhxh, ref Maxqt1, ref  Maxqt) == false) { return; }
                    }

                    //Dua qua trinh vao dataset qua trinh tam va lay thang bat dau trong qua trinh tham gia
                    thangbdMin = GetQuaTrinhVaThangBatDauQuaTrinh(sobhxh, dsTQuatrinh, thangbdMin, Maxqt1);
                    
                    //so sanh voi qua trinh da in to roi de lay thang bd
                    thangbd = GetThangBatDau(thangbdMin, sobhxh, k);
                                        
                    //set thangtk dua tren thang bd - 100 (de phuc vu viec tang in to roi theo nam)
                    thangkt = Convert.ToString(Convert.ToInt32(thangbd.Substring(0,4)) - 1) + "12";
                    //bat dau sap xep qua trinh
                    while (Convert.ToInt32(thangbd) <= Convert.ToInt32(Maxqt))
                    {
                        thangkt = Convert.ToString(Convert.ToInt32(thangkt) + 100);//thang thangkt len 100
                        thanggh = thangkt;
                        if (Convert.ToInt32(thangkt) >= Convert.ToInt32(Maxqt)) //thang kt lon hon Maxqt gan thang ket = Maxqt
                        {
                            if (sender == null) //in to roi hang nam
                            {
                                if (flag == true) //co chot so
                                {
                                    thangkt = Maxqt;
                                    xacnhan = FlxSobhxh.Rows[k]["xacnhan"].ToString(); //Gan loai XN
                                }
                                else //khong chot so
                                {
                                    xacnhan = "";
                                }
                            }
                            else //in to roi chot so
                            {
                                thangkt = Maxqt;
                                xacnhan = FlxSobhxh.Rows[k]["xacnhan"].ToString(); //Gan loai XN
                            }
                        }
                        else 
                        {
                            if (sender == null) //tao to roi hang nam
                            {
                                xacnhan = "";
                            }
                            else
                            {
                                xacnhan = "QT";
                            }
                        }//Gian lai XN = Qua Trinh

                        dsQuatrinh.Tables[0].Clear(); // clear dataset 
                        //Sap Xep Qua Trinh

                        dsQuatrinh = SapXepQuaTrinh(dsTQuatrinh, thanggh, Maxqt, k);
                       // test(dsTQuatrinh);
                        //chen them donvi cho cac dong ko co ten don vi
                        SetTenDonVi(dsQuatrinh, sobhxh, Maxqt, k);
                        //them dong de hoan thanh qua trinh
                        ThemQuaTrinh(dsQuatrinh, thangkt);
                        //merge
                        MergeQuaTrinh(dsQuatrinh);
                        //cat theo ti le bhxh
                        CatTileQuaTrinh(dsQuatrinh);

                        //them dong khong tham gia và cắt các dòng có thời gian trung nhau
                        ThemKhongThamGiaQuaTrinh(dsQuatrinh);

                        flagdulieu = false; //kiem tra trong nam khong co du lieu phat sinh
                        nam = 0;
                        thang = 0;
                        tuthangxn = "";

                        //dua va dataset dsKQuaTrinh
                        GetDuLieuDSKetQua(dsQuatrinh, k, xacnhan, thangbd, thangkt, ref tuthangxn, ref nam, ref thang, ref flagdulieu);

                        //them dong ko tham gia cho den het thang ket thuc
                        if (dsQuatrinh.Tables[0].Rows.Count > 0 && Convert.ToInt32(dsQuatrinh.Tables[0].Rows[dsQuatrinh.Tables[0].Rows.Count - 1]["DENTHANG"]) >= Convert.ToInt32(thangbd)
                                && Convert.ToInt32(dsQuatrinh.Tables[0].Rows[dsQuatrinh.Tables[0].Rows.Count - 1]["TUTHANG"]) <= Convert.ToInt32(thangkt)
                                && Convert.ToInt32(dsQuatrinh.Tables[0].Rows[dsQuatrinh.Tables[0].Rows.Count - 1]["DENTHANG"]) < Convert.ToInt32(thangkt))
                        {
                            SetDongKhongThamGia(sobhxh, thangbd,
                                (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[dsQuatrinh.Tables[0].Rows.Count - 1]["DENTHANG"]) + 1).ToString(),
                                thangkt);

                        }
                        //thang bat dau lon hon max thang ket thuc trong qua trinh
                        else if (dsQuatrinh.Tables[0].Rows.Count > 0 &&
                            Convert.ToInt32(dsQuatrinh.Tables[0].Rows[dsQuatrinh.Tables[0].Rows.Count - 1]["DENTHANG"]) < Convert.ToInt32(thangbd))
                        {
                            SetDongKhongThamGia(sobhxh, thangbd, thangbd, thangkt);
                        }
                        //dua du lieu vao luoi flxdetail
                        if (flagdulieu == true)//truong hop co chi tiet trong khoang thoi gian 
                        {

                            GetDataOnFlex(k, thangbd, thangkt, xacnhan, nam, thang, tuthangxn);
                            Bhtn_hangnam(k, xacnhan, thangbd, thangkt, thanggh, Maxqt1);

                        }
                        // set lai thang bat dau
                        thangbd = (Convert.ToInt32(thangkt.Substring(0, 4)) + 1).ToString();
                        thangbd = thangbd + "01";

                    }//ket thuc while

                }
            }

            flageFlex = 2;
            Cursor.Current = Cursors.Default;
        }
        /// <summary>
        /// tao to roi sau khi da kiem tra xong
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTaotoroi_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            string keysl, queryString,strPa="";
            using (SqlConnection connection =
               new SqlConnection(connectionString1))
            {
                SqlCommand command = connection.CreateCommand();
                connection.Open();
                for (int i = 1; i < FlxDetail.Rows.Count; i++)
                {
                    if (Convert.ToInt16(FlxDetail.Rows[i]["CHECK"]) == 1)
                    {
                        keysl = ModuleBHXH.CreateRunninNo(rnd);
                        queryString = "exec sp_executesql N'INSERT INTO dbo.INTR_HDR (KEYSL,SOBHXH,HO,TEN,MADVI,LOAIIN,LOAI,NGAYCAP,THANGBD,THANGKT,"
                        + " THANGHT,LOAIXN,TUTHANGXN,DENTHANGXN,SONAMXN,SOTHANGXN,TT_XNTNG,DT_XNTNG,SN_XNTNG,ST_XNTNG,LANCAP,MAPB,USERCODE,"
                        + " MA_QUAN,LOAIDC,DTDONVI) VALUES (@P1,@P2,@P3,@P4,@P5,@P6,@P7,@P8,@P9,@P10,@P11,@P12,@P13,@P14,@P15,@P16,@P17,@P18,@P19,@P20,"
                        + " @P21,@P22,@P23,@P24,@P25,@P26)', N'@P1 char(22),@P2 char(16),@P3 varchar(30),@P4 varchar(20),@P5 char(7),"
                        + " @P6 char(1),@P7 char(1),@P8 smalldatetime,@P9 char(6),@P10 char(6),@P11 char(6),@P12 char(2),@P13 char(6),@P14 char(6),"
                        + " @P15 smallint,@P16 smallint,@P17 char(6),@P18 char(6),@P19 smallint,@P20 smallint,@P21 smallint,@P22 varchar(30),"
                        + " @P23 char(10),@P24 char(2),@P25 char(1),@P26 char(26)', '" + keysl + "', '" + FlxDetail.Rows[i]["Sobhxh"] + "', "
                        + " '" + FlxDetail.Rows[i]["Ho"] + "', '" + FlxDetail.Rows[i]["Ten"] + "', '" + FlxDetail.Rows[i]["Madvi"] + "', 'B', '1', '" + BHXH_NT.ModuleBHXH.strDate + "',"
                        + " '" + FlxDetail.Rows[i]["tuthang"] + "','" + FlxDetail.Rows[i]["denthang"] + "','" + FlxDetail.Rows[i]["dongden"] + "', '" + FlxDetail.Rows[i]["xacnhan"] + "',"
                        + " '" + FlxDetail.Rows[i]["tuthangxn"] + "', '" + FlxDetail.Rows[i]["denthangxn"] + "'," + FlxDetail.Rows[i]["sonam"] + "," + FlxDetail.Rows[i]["sothang"] + ","
                        + " '" + FlxDetail.Rows[i]["tuthangxntn"] + "', '" + FlxDetail.Rows[i]["denthangxntn"] + "'," + FlxDetail.Rows[i]["sonamtn"] + ", " + FlxDetail.Rows[i]["sothangtn"] + ","
                        + " 1, '                              ','" + ModuleBHXH.strUser + "', '01', ' ','" + FlxDetail.Rows[i]["DTdonvi"] + "'";

                        command.CommandText = queryString;
                        command.ExecuteNonQuery();

                        DataRow[] foundRows;
                        foundRows = dsKQuatrinh.Tables[0].Select("Sobhxh = '" + FlxDetail.Rows[i]["Sobhxh"].ToString().Trim() + "' and maqt = '" + FlxDetail.Rows[i]["tuthang"].ToString() + "'");
                        foreach (DataRow foundRow in foundRows)
                        {
                            if (foundRow["pa"].ToString() == "TS" || foundRow["pa"].ToString() == "TM" || foundRow["pa"].ToString() == "ON") 
                            { strPa = foundRow["pa"].ToString();} 
                            else
                            { strPa = ""; }  

                            if (foundRow["TLBHXH"].ToString() != "3")
                            {
                                
                                queryString = "exec sp_executesql N'INSERT INTO dbo.INTR_DTL (KEYSL,KEYP,MADVI,TUTHANG,DENTHANG,LOAIDT,MA_NTE,PA,ML,HSL,PC1,PC2,PC3,PC4,"
                                + " PC5,TYLE_BHXH,TYLE_BHTN,NOIDUNG,MA_QUAN,USERCODE) VALUES (@P1,@P2,@P3,@P4,@P5,@P6,@P7,@P8,@P9,@P10,@P11,@P12,@P13,@P14,"
                                + " @P15,@P16,@P17,@P18,@P19,@P20)', N'@P1 char(22),@P2 char(8),@P3 char(7),@P4 char(6),@P5 char(6),@P6 char(2),@P7 char(3),"
                                + " @P8 char(2),@P9 numeric(18,3),@P10 numeric(6,3),@P11 numeric(6,3),@P12 numeric(6,3),@P13 numeric(6,3),@P14 numeric(6,3),"
                                + " @P15 numeric(6,3),@P16 numeric(6,3),@P17 numeric(6,3),@P18 varchar(250),@P19 char(2),@P20 char(10)', "
                                + " '" + keysl + "', '" + ModuleBHXH.CreateRunninNo1(rnd) + " ', '" + foundRow["Madvi"] + "', '" + foundRow["Tuthang"].ToString() + "',"
                                + " '" + foundRow["DenThang"].ToString() + "', '" + foundRow["Loaidt"] + "', '" + foundRow["Ma_nte"] + "', '" + strPa  + "', "
                                + ModuleBHXH.FormatNumner(foundRow["MUCLUONG"]) + "," + ModuleBHXH.FormatNumner(foundRow["HSL"]) + ", " + ModuleBHXH.FormatNumner(foundRow["PCCV"]) + ", " 
                                + ModuleBHXH.FormatNumner(foundRow["PCTN"]) + ", " + ModuleBHXH.FormatNumner(foundRow["PCNG"]) + ", " + ModuleBHXH.FormatNumner(foundRow["PCKV"]) + ",  0.000,"
                                + foundRow["TLBHXH"] + ",0.000, '" + foundRow["Congviec"] + "',"
                                + " '01', '" + ModuleBHXH.strUser + "'";
                            }
                            else
                            {
                                queryString = "exec sp_executesql N'INSERT INTO dbo.INTR_DTL (KEYSL,KEYP,MADVI,TUTHANG,DENTHANG,LOAIDT,MA_NTE,PA,ML,HSL,PC1,PC2,PC3,PC4,"
                               + " PC5,TYLE_BHXH,TYLE_BHTN,NOIDUNG,MA_QUAN,USERCODE) VALUES (@P1,@P2,@P3,@P4,@P5,@P6,@P7,@P8,@P9,@P10,@P11,@P12,@P13,@P14,"
                               + " @P15,@P16,@P17,@P18,@P19,@P20)', N'@P1 char(22),@P2 char(8),@P3 char(7),@P4 char(6),@P5 char(6),@P6 char(2),@P7 char(3),"
                               + " @P8 char(2),@P9 numeric(18,3),@P10 numeric(6,3),@P11 numeric(6,3),@P12 numeric(6,3),@P13 numeric(6,3),@P14 numeric(6,3),"
                               + " @P15 numeric(6,3),@P16 numeric(6,3),@P17 numeric(6,3),@P18 varchar(250),@P19 char(2),@P20 char(10)', "
                               + " '" + keysl + "', '" + ModuleBHXH.CreateRunninNo1(rnd) + " ', '" + foundRow["Madvi"] + "', '" + foundRow["Tuthang"].ToString() + "',"
                               + " '" + foundRow["DenThang"].ToString() + "', '" + foundRow["Loaidt"] + "', '" + foundRow["Ma_nte"] + "', '" + strPa + "', "
                               + ModuleBHXH.FormatNumner(foundRow["MUCLUONG"]) + "," + ModuleBHXH.FormatNumner(foundRow["HSL"]) + ", " + ModuleBHXH.FormatNumner(foundRow["PCCV"]) + ", " 
                               + ModuleBHXH.FormatNumner(foundRow["PCTN"]) + ", " + ModuleBHXH.FormatNumner(foundRow["PCNG"]) + ", " + ModuleBHXH.FormatNumner(foundRow["PCKV"]) + ",  0.000,"
                               + "0.000 ," + foundRow["TLBHXH"] + ", '" + foundRow["Congviec"] + "',"
                               + " '01', '" + ModuleBHXH.strUser + "'";
                            }
                            command.CommandText = queryString;
                            command.ExecuteNonQuery();

                        }

                    }//ket thu if
                    
                }//ket thuc for
              
            }//ket thuc using
            //btnkiemtra_Click(null, null);
            if (sender != null)
            {
                btnTaosolieu_Click(btnTaosolieu, null);
            }
            else
            {
                txtSolieuHN_Click(btnSolieuHN, null);
            }
            Cursor.Current = Cursors.Default;
        }
        private void FrmInToRoi_Load(object sender, EventArgs e)
        {
            dtTungay.Value = DateTime.Now.Day.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Year.ToString();
            dtDenngay.Value = DateTime.Now.Day.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.Year.ToString();
            txtNamGiam.Text = DateTime.Now.Year.ToString();
        }
        /// <summary>
        /// cap nhat so thu tu de in theo thu tu da chon
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FlxSobhxh_Click(object sender, EventArgs e)
        {
            if (FlxSobhxh.Selection.TopRow>0)
            {
                if (FlxSobhxh.Rows[FlxSobhxh.Selection.TopRow]["Check"] != null &&
                    FlxSobhxh.Rows[FlxSobhxh.Selection.TopRow]["STT"] == null &&
                    Convert.ToBoolean(FlxSobhxh.Rows[FlxSobhxh.Selection.TopRow]["Check"]) == true)
                {
                    intSochay++;
                    FlxSobhxh.Rows[FlxSobhxh.Selection.TopRow]["STT"] = intSochay;
                }
                else if (Convert.ToBoolean(FlxSobhxh.Rows[FlxSobhxh.Selection.TopRow]["Check"]) == false)
                {
                    FlxSobhxh.Rows[FlxSobhxh.Selection.TopRow]["STT"] = null;
                }
            }
        }
        /// <summary>
        /// hien thi danh sach so bhxh chua cap to roi duoc user chon in
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSoLieuChon_Click(object sender, EventArgs e)
        {
            int i = 1;
            string queryString;
            Cursor.Current = Cursors.WaitCursor;
            queryString = "SELECT a.Sobhxh,c.Ho, c.Ten, a.Madvi,c.macv,d.diachi,d.tendvi,a.xacnhan "
            + " FROM HOSOCN c "
            + " inner join MISBHXH_SOTHE_NT.dbo.INTR_BL a on a.Sobhxh = c.sobhxh"
            + " inner join MISBHXH_NT.dbo.DMDONVI d on d.Madvi = a.Madvi";


            FlxSobhxh.Rows.Count = 1;
            FlxDetail.Rows.Count = 1;
            faQuaTrinh.Rows.Count = 1;
            intSochay = 0;
            using (SqlConnection connection =
                  new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = queryString;
                command.CommandTimeout = 3600;
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    FlxSobhxh.Rows.Count = FlxSobhxh.Rows.Count + 1;
                    FlxSobhxh.Rows[i]["Madvi"] = reader["Madvi"];
                    FlxSobhxh.Rows[i]["Tendvi"] = reader["Tendvi"];
                    FlxSobhxh.Rows[i]["Sobhxh"] = reader["Sobhxh"];
                    FlxSobhxh.Rows[i]["Sobhxh1"] = reader["Sobhxh"].ToString().Trim().Substring(6);
                    FlxSobhxh.Rows[i]["Ho"] = reader["Ho"];
                    FlxSobhxh.Rows[i]["Ten"] = reader["Ten"];
                    FlxSobhxh.Rows[i]["macv"] = reader["macv"];
                    FlxSobhxh.Rows[i]["Diachi"] = reader["Diachi"];
                    FlxSobhxh.Rows[i]["Xacnhan"] = reader["Xacnhan"];
                    FlxSobhxh.Rows[i]["Tuthang"] = "200901";
                    i++;
                }
                reader.Close();
            }
            Cursor.Current = Cursors.Default;
        }
        /// <summary>
        /// xoa danh sach trong table INTR_BL
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnXoa_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            string queryString, Condition = "";
            for (int i = 1; i < FlxSobhxh.Rows.Count; i++)
            {
                if (FlxSobhxh.Rows[i]["Check"] != null && FlxSobhxh.Rows[i]["Check"].ToString() == "True")
                {
                    Condition = Condition + "'" + FlxSobhxh.Rows[i]["sobhxh"] + "',";
                }
            }
            if (Condition == "") { return; }
            Condition = Condition.Substring(0, Condition.Length - 1);
            using (SqlConnection connection =
                   new SqlConnection(connectionString1))
            {
                connection.Open();
                SqlCommand command = connection.CreateCommand();
                queryString = "delete " + Settings.Default.DBName_Sothe + ".dbo.INTR_BL where sobhxh IN (" + Condition + ")";
                command.CommandText = queryString;
                command.ExecuteNonQuery();

            }
            MessageBox.Show("Xãa danh s¸ch thµnh c«ng");
            btnSoLieuChon_Click(null, null);
            Cursor.Current = Cursors.Default;
        }
        /// <summary>
        /// test qua trinh tren luoi
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        private void test(QuatrinhBHXH dsQuatrinh)
        {
            faQuaTrinh.Rows.Count = 1;
            for (int i = 0; i <= dsQuatrinh.Tables[0].Rows.Count - 1; i++)
            {

                faQuaTrinh.Rows.Count = faQuaTrinh.Rows.Count + 1;
                faQuaTrinh.Rows[i]["Madvi"] = dsQuatrinh.Tables[0].Rows[i]["Madvi"];
                faQuaTrinh.Rows[i]["Loai"] = dsQuatrinh.Tables[0].Rows[i]["Maqt"];
                faQuaTrinh.Rows[i]["tuthang"] = dsQuatrinh.Tables[0].Rows[i]["tuthang"];
                faQuaTrinh.Rows[i]["denthang"] = dsQuatrinh.Tables[0].Rows[i]["denthang"];
                faQuaTrinh.Rows[i]["pa"] = dsQuatrinh.Tables[0].Rows[i]["pa"];
                faQuaTrinh.Rows[i][6] = dsQuatrinh.Tables[0].Rows[i]["congviec"];
                faQuaTrinh.Rows[i][7] = dsQuatrinh.Tables[0].Rows[i]["mucluong"];
                faQuaTrinh.Rows[i][8] = dsQuatrinh.Tables[0].Rows[i]["HSL"];


            }
        }
        /// <summary>
        /// Update ngay in to roi
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSLton_Click(object sender, EventArgs e)
        {
            string queryString;
            string strMadviTam = "";
            int soluong = 0;
            using (SqlConnection connection =
               new SqlConnection(connectionString1))
            {
                SqlCommand command = connection.CreateCommand();
                connection.Open();
                for (int i = 1; i < FlxDetail.Rows.Count; i++)
                {
                    queryString = " exec sp_executesql N'UPDATE dbo.INTR_HDR SET DAIN=@P1,NGAYIN=@P2,USERIN=@P3 "
                    + " WHERE KEYSL=@P4', N'@P1 smallint,@P2 smalldatetime,@P3 varchar(10),@P4 char(22)'"
                    + ", 1, '" + ModuleBHXH.GetDate() + "', '" + ModuleBHXH.strUser + "', '" + FlxDetail.Rows[i]["KEYSL"].ToString().Trim() + "'";

                    command.CommandText = queryString;
                    command.ExecuteNonQuery();
                }

                // insert CTUVT_SD
                FlxDetail.Sort(SortFlags.Ascending, 4);
                for (int i = 1; i < FlxDetail.Rows.Count; i++)
                {
                    if (strMadviTam != FlxDetail.Rows[i]["Madvi"].ToString())
                    {
                        if (soluong != 0 && CheckSoLuongToRoi(soluong) > 0)
                        {
                            queryString = "exec sp_executesql N'INSERT INTO dbo.CTUVT_SD "
                            + " (SOCT,NGAYCT,NX,MAKHO,MAVT,SOLUONG,TUSO,DENSO,NOIDUNG,USERCODE,KEYSL) "
                            + " VALUES (@P1,@P2,@P3,@P4,@P5,@P6,@P7,@P8,@P9,@P10,@P11)', "
                            + " N'@P1 char(10),@P2 smalldatetime,@P3 char(1),@P4 char(10),@P5 char(10),@P6 numeric(18,0),"
                            + " @P7 varchar(15),@P8 varchar(15),@P9 varchar(100),@P10 char(10),@P11 char(20)', "
                            + " '          ', '" + ModuleBHXH.GetDate() + " ', 'X', 'QLS       ', 'RT        ', " + soluong + ", "
                            + "'               ', '               ', 'CÊp tê rêi cho ®¬n vÞ " + strMadviTam + "', "
                            + " '" + ModuleBHXH.strUser + "', '" + ModuleBHXH.CreateRunninNo(rnd) + "'";


                            command.CommandText = queryString;
                            command.ExecuteNonQuery();
                        }
                        strMadviTam = FlxDetail.Rows[i]["Madvi"].ToString();
                        soluong = 1;
                    }
                    else
                    {
                        soluong++;
                    }
                }
                if (soluong != 0 && CheckSoLuongToRoi(soluong) > 0)
                {
                    queryString = "exec sp_executesql N'INSERT INTO dbo.CTUVT_SD "
                    + " (SOCT,NGAYCT,NX,MAKHO,MAVT,SOLUONG,TUSO,DENSO,NOIDUNG,USERCODE,KEYSL) "
                    + " VALUES (@P1,@P2,@P3,@P4,@P5,@P6,@P7,@P8,@P9,@P10,@P11)', "
                    + " N'@P1 char(10),@P2 smalldatetime,@P3 char(1),@P4 char(10),@P5 char(10),@P6 numeric(18,0),"
                    + " @P7 varchar(15),@P8 varchar(15),@P9 varchar(100),@P10 char(10),@P11 char(20)', "
                    + " '          ', '" + ModuleBHXH.GetDate() + " ', 'X', 'QLS       ', 'RT        ', " + soluong + ", "
                    + "'               ', '               ', 'CÊp tê rêi cho ®¬n vÞ " + strMadviTam + "', "
                    + " '" + ModuleBHXH.strUser + "', '" + ModuleBHXH.CreateRunninNo(rnd) + "'";
                    command.CommandText = queryString;
                    command.ExecuteNonQuery();
                }
                else if (soluong != 0)
                {
                    MessageBox.Show("xuất quá số lượng tờ rời");
                }

                FlxDetail.Rows.Count = 1;
            }
        }
        #endregion

        #region "Private Method"
        private void CheckKhongThamGia(string sobhxh,string thangbd,int i)
        {
            DataRow[] foundRows;
                       
            foundRows = dsKQuatrinh.Tables[0].Select("Sobhxh = '" + sobhxh.ToString().Trim() + "' and maqt = '" + thangbd + "'", "Tuthang");
            		
            if (foundRows.Length  == 1 && foundRows[0]["congviec"].ToString().Trim() == "Kh«ng Tham Gia")
            {
                C1.Win.C1FlexGrid.CellStyle rs = this.FlxDetail.Styles.Add("rowcolor");
                rs.ForeColor = Color.Brown;
                FlxDetail.Rows[i].Style = rs;
            }
            foreach (DataRow foundRow in foundRows)
            {
                if (foundRow["Madvi"].ToString() != FlxDetail.Rows[i]["Madvi"].ToString())
                {
                    C1.Win.C1FlexGrid.CellStyle rs = this.FlxDetail.Styles.Add("rowcolor");
                    rs.ForeColor = Color.Brown;
                    FlxDetail.Rows[i].Style = rs;
                }
            }

        }
        /// <summary>
        /// them dong khong tham gia
        /// </summary>
        /// <param name="Sobhxh"></param>
        /// <param name="thangbd"></param>
        /// <param name="tuthang"></param>
        /// <param name="denthang"></param>
        private void SetDongKhongThamGia(string Sobhxh,string thangbd,string tuthang,string denthang)
        {
            DataRow newRow;
            newRow = dsKQuatrinh.Tables[0].NewRow();
            newRow["Maqt"] = thangbd;
            newRow["SOBHXH"] = Sobhxh;
            newRow["Tuthang"] = tuthang;
            newRow["DenThang"] = denthang;
            newRow["Mucluong"] = 0;
            newRow["Hsl"] = 0;
            newRow["PCCV"] = 0;
            newRow["PCTN"] = 0;
            newRow["PCNG"] = 0;
            newRow["PCKV"] = 0;
            newRow["TLBHXH"] = 0;
            newRow["pa"] = "OF";
            newRow["Congviec"] = "Kh«ng tham gia";
            newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
              Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
            dsKQuatrinh.Tables[0].Rows.Add(newRow);
        }
        /// <summary>
        /// Dua du lieu vao data set ket qua
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        /// <param name="k"></param>
        /// <param name="xacnhan"></param>
        /// <param name="thangbd"></param>
        /// <param name="thangkt"></param>
        /// <param name="tuthangxn"></param>
        /// <param name="nam"></param>
        /// <param name="thang"></param>
        /// <param name="flagdulieu"></param>
        private void GetDuLieuDSKetQua(QuatrinhBHXH dsQuatrinh, int k, string xacnhan,string thangbd,string thangkt,
            ref string tuthangxn,ref int nam,ref int thang,ref bool flagdulieu)
        {
            int i;
            DataRow newRow;
            //dua va dataset dsKQuaTrinh
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {
                //truong hop day la dong chot so
                if (xacnhan == FlxSobhxh.Rows[k]["xacnhan"].ToString() && xacnhan != "")
                {
                    if (i == 0)
                    {
                        tuthangxn = dsQuatrinh.Tables[0].Rows[i]["TUTHANG"].ToString();
                    }
                    //chi tinh thoi gian tham gia bhxh
                    if (dsQuatrinh.Tables[0].Rows[i]["Tendvi"].ToString() != "Kh«ng tham gia")
                    {
                        ModuleBHXH.KhoangThoiGian(ModuleBHXH.FormatThangNam(dsQuatrinh.Tables[0].Rows[i]["TUTHANG"].ToString()),
                             ModuleBHXH.FormatThangNam(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"].ToString()), ref nam, ref thang);
                    }
                }
                if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"]) >= Convert.ToInt32(thangbd)
                    && Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["TUTHANG"]) <= Convert.ToInt32(thangkt))
                {
                    flagdulieu = true;
                    if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["TUTHANG"]) < Convert.ToInt32(thangbd))
                    {
                        dsQuatrinh.Tables[0].Rows[i]["TUTHANG"] = thangbd;
                    }
                    if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"]) > Convert.ToInt32(thangkt))
                    {
                        dsQuatrinh.Tables[0].Rows[i]["DENTHANG"] = thangkt;
                    }

                    newRow = dsKQuatrinh.Tables[0].NewRow();
                    newRow["Maqt"] = thangbd;
                    newRow["Madvi"] = dsQuatrinh.Tables[0].Rows[i]["Madvi"];
                    newRow["SOBHXH"] = FlxSobhxh.Rows[k]["SOBHXH"];
                    newRow["TUTHANG"] = dsQuatrinh.Tables[0].Rows[i]["TUTHANG"].ToString();
                    newRow["DENTHANG"] = dsQuatrinh.Tables[0].Rows[i]["DENTHANG"].ToString();
                    newRow["loaidt"] = dsQuatrinh.Tables[0].Rows[i]["loaidt"];
                    newRow["ma_nte"] = dsQuatrinh.Tables[0].Rows[i]["ma_nte"];
                    newRow["mucluong"] = dsQuatrinh.Tables[0].Rows[i]["mucluong"];
                    newRow["hsl"] = dsQuatrinh.Tables[0].Rows[i]["hsl"];
                    newRow["PCCV"] = dsQuatrinh.Tables[0].Rows[i]["PCCV"];
                    newRow["PCTN"] = dsQuatrinh.Tables[0].Rows[i]["PCTN"];
                    newRow["PCNG"] = dsQuatrinh.Tables[0].Rows[i]["PCNG"];
                    newRow["PCKV"] = dsQuatrinh.Tables[0].Rows[i]["PCKV"];
                    newRow["sothang"] = dsQuatrinh.Tables[0].Rows[i]["sothang"];
                    newRow["pa"] = dsQuatrinh.Tables[0].Rows[i]["pa"];
                    if (dsQuatrinh.Tables[0].Rows[i]["Congviec"].ToString().Trim() == "")
                    {
                        if (dsQuatrinh.Tables[0].Rows[i]["PA"].ToString() == "TS" || dsQuatrinh.Tables[0].Rows[i]["PA"].ToString() == "OF" || dsQuatrinh.Tables[0].Rows[i]["PA"].ToString() == "GD")
                        {
                            newRow["Congviec"] = dsQuatrinh.Tables[0].Rows[i]["Tendvi"].ToString().Trim();
                        }
                        else
                        {
                            newRow["Congviec"] = ModuleBHXH.ChangeToCamel(dsQuatrinh.Tables[0].Rows[i]["Tendvi"].ToString().Trim());
                        }

                    }
                    else
                    {
                        newRow["Congviec"] = ModuleBHXH.ChangeToCamel(dsQuatrinh.Tables[0].Rows[i]["Congviec"].ToString().Trim() + ". " + dsQuatrinh.Tables[0].Rows[i]["Tendvi"].ToString().Trim()
                            + ". " + dsQuatrinh.Tables[0].Rows[i]["DiaChi"].ToString().Trim());
                    }

                    if (dsQuatrinh.Tables[0].Rows[i]["PA"].ToString() != "TS"
                        && dsQuatrinh.Tables[0].Rows[i]["PA"].ToString() != "OF"
                        && dsQuatrinh.Tables[0].Rows[i]["PA"].ToString() != "GH"
                        && dsQuatrinh.Tables[0].Rows[i]["PA"].ToString() != "GD")
                    {
                        if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"]) <= 199412)
                        {
                            newRow["TLBHXH"] = "";
                        }
                        else if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"]) <= 200912)
                        {
                            newRow["TLBHXH"] = string.Format("{0:##}", 20);
                        }
                        else
                        {
                            newRow["TLBHXH"] = string.Format("{0:##}", 22);
                        }
                    }
                    else
                    {
                        newRow["TLBHXH"] = 0;
                    }
                    dsKQuatrinh.Tables[0].Rows.Add(newRow);

                }
            }//ket thuc dua vao dataset
        }
        /// <summary>
        /// Them khong tham gia qua trinh
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        private void ThemKhongThamGiaQuaTrinh(QuatrinhBHXH dsQuatrinh)
        {
            int i;
            DataRow oldRow = null;
            DataRow newRow = null;
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
            {
                oldRow = dsQuatrinh.Tables[0].Rows[i];
                newRow = dsQuatrinh.Tables[0].Rows[i + 1];
                //cat cac dong co thoi gian trung
                if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) <= 0)
                {
                    oldRow["Denthang"] = Convert.ToInt32(newRow["Tuthang"]) - 1;
                    if (oldRow["DenThang"].ToString().Substring(4) == "00")
                    {
                        oldRow["DenThang"] = Convert.ToInt32(oldRow["DenThang"].ToString().Substring(0, 4)) - 1;
                        oldRow["DenThang"] = oldRow["DenThang"].ToString() + "12";
                    }
                    oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                         Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                }
                //them dong ko tham gia
                else if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) > 1)
                {
                    DataRow ktgRow = dsQuatrinh.Tables[0].NewRow();
                    //newRow["Madvi"] = oldRow["Madvi"];
                    ktgRow["Tuthang"] = Convert.ToInt32(oldRow["denThang"]) + 1;
                    if (ktgRow["Tuthang"].ToString().Substring(4) == "13")
                    {
                        ktgRow["Tuthang"] = Convert.ToInt32(ktgRow["Tuthang"].ToString().Substring(0, 4)) + 1;
                        ktgRow["Tuthang"] = ktgRow["Tuthang"].ToString() + "01";
                    }
                    ktgRow["DenThang"] = Convert.ToInt32(newRow["Tuthang"].ToString()) - 1;

                    if (ktgRow["DenThang"].ToString().Substring(4) == "00")
                    {
                        ktgRow["DenThang"] = Convert.ToInt32(ktgRow["DenThang"].ToString().Substring(0, 4)) - 1;
                        ktgRow["DenThang"] = ktgRow["DenThang"].ToString() + "12";
                    }
                    ktgRow["Mucluong"] = 0;
                    ktgRow["Hsl"] = 0;
                    ktgRow["PCCV"] = 0;
                    ktgRow["PCTN"] = 0;
                    ktgRow["PCNG"] = 0;
                    ktgRow["PCKV"] = 0;

                    ktgRow["pa"] = "OF";
                    ktgRow["Tendvi"] = "Kh«ng tham gia";
                    ktgRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(ktgRow["Tuthang"].ToString().Substring(0, 4) + "/" + ktgRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                      Convert.ToDateTime(ktgRow["Denthang"].ToString().Substring(0, 4) + "/" + ktgRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                    dsQuatrinh.Tables[0].Rows.InsertAt(ktgRow, i + 1);


                }
            }//ket thuc them dong khong tham gia và cắt các dòng có thời gian trung nhau
        }
        /// <summary>
        /// Cat qua trinh Theo ti le dong bhxh
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        private void CatTileQuaTrinh(QuatrinhBHXH dsQuatrinh)
        {
            int i;
            DataRow oldRow = null;
            DataRow newRow = null;
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {
                oldRow = dsQuatrinh.Tables[0].Rows[i];
                if (oldRow["Denthang"] is System.DBNull) { break; }
                if (Convert.ToInt32(oldRow["denThang"].ToString()) > 199412 && Convert.ToInt32(oldRow["tuThang"].ToString()) <= 199412
                    && oldRow["pa"].ToString() != "GH"
                    && oldRow["pa"].ToString() != "TS"
                    && oldRow["pa"].ToString() != "OF"
                    && oldRow["pa"].ToString() != "GD")
                {

                    newRow = dsQuatrinh.Tables[0].NewRow();
                    newRow["Madvi"] = oldRow["Madvi"];
                    newRow["Tuthang"] = oldRow["Tuthang"];
                    newRow["Denthang"] = oldRow["Denthang"];
                    newRow["Loaidt"] = oldRow["Loaidt"];
                    newRow["Ma_nte"] = oldRow["Ma_nte"];
                    newRow["Mucluong"] = oldRow["Mucluong"];
                    newRow["Hsl"] = oldRow["Hsl"];
                    newRow["PCCV"] = oldRow["PCCV"];
                    newRow["PCTN"] = oldRow["PCTN"];
                    newRow["PCNG"] = oldRow["PCNG"];
                    newRow["PCKV"] = oldRow["PCKV"];
                    newRow["pa"] = oldRow["pa"];
                    newRow["Congviec"] = oldRow["Congviec"];
                    newRow["Tendvi"] = oldRow["Tendvi"];
                    newRow["Diachi"] = oldRow["Diachi"];
                    oldRow["denthang"] = "199412";
                    oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                          Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                    newRow["tuThang"] = "199501";
                    newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                          Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                    dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);

                }
                else if (Convert.ToInt32(oldRow["denThang"].ToString()) > 200912 && Convert.ToInt32(oldRow["tuThang"].ToString()) <= 200912 &&
                    oldRow["pa"].ToString() != "GH" &&
                    oldRow["pa"].ToString() != "TS" &&
                    oldRow["pa"].ToString() != "OF" &&
                    oldRow["pa"].ToString() != "GD")
                {

                    newRow = dsQuatrinh.Tables[0].NewRow();
                    newRow["Madvi"] = oldRow["Madvi"];
                    newRow["Tuthang"] = oldRow["Tuthang"];
                    newRow["Denthang"] = oldRow["Denthang"];
                    newRow["Loaidt"] = oldRow["Loaidt"];
                    newRow["Ma_nte"] = oldRow["Ma_nte"];
                    newRow["Mucluong"] = oldRow["Mucluong"];
                    newRow["Hsl"] = oldRow["Hsl"];
                    newRow["PCCV"] = oldRow["PCCV"];
                    newRow["PCTN"] = oldRow["PCTN"];
                    newRow["PCNG"] = oldRow["PCNG"];
                    newRow["PCKV"] = oldRow["PCKV"];
                    newRow["pa"] = oldRow["pa"];
                    newRow["Congviec"] = oldRow["Congviec"];
                    newRow["Tendvi"] = oldRow["Tendvi"];
                    newRow["Diachi"] = oldRow["Diachi"];
                    oldRow["denthang"] = "200912";
                    oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                          Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                    newRow["tuThang"] = "201001";
                    newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                          Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                    dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                    break;
                }
            }//ket thuc cat ti le bhxh
        }
        /// <summary>
        /// Merge cac khoang qua trinh trung nhau
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        private void MergeQuaTrinh(QuatrinhBHXH dsQuatrinh)
        {
            int i;
            DataRow oldRow = null;
            DataRow newRow = null;
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
            {
                oldRow = dsQuatrinh.Tables[0].Rows[i];
                newRow = dsQuatrinh.Tables[0].Rows[i + 1];
                if (oldRow["Denthang"] is System.DBNull) { break; }
                if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) == 1)
                {

                    if (oldRow["Mucluong"].ToString() == newRow["Mucluong"].ToString() &&
                        oldRow["HSL"].ToString() == newRow["HSL"].ToString() &&
                         oldRow["PCCV"].ToString() == newRow["PCCV"].ToString() &&
                         oldRow["PCTN"].ToString() == newRow["PCTN"].ToString() &&
                         oldRow["PCNG"].ToString() == newRow["PCNG"].ToString() &&
                         oldRow["PCKV"].ToString() == newRow["PCKV"].ToString() &&
                         oldRow["PCCV"].ToString() == newRow["PCCV"].ToString() &&
                        //oldRow["Pa"].ToString() == newRow["Pa"].ToString() &&
                         oldRow["Congviec"].ToString().ToUpper().Trim() == newRow["Congviec"].ToString().ToUpper().Trim() &&
                         oldRow["Tendvi"].ToString() == newRow["Tendvi"].ToString())
                    {
                        newRow["Tuthang"] = oldRow["Tuthang"];
                        newRow["Sothang"] = Convert.ToInt32(newRow["Sothang"]) + Convert.ToInt32(oldRow["Sothang"]);
                        oldRow.Delete();
                        i = i - 1;
                    }
                }
                //Xoa dong trung
                else if (Convert.ToInt32(oldRow["tuThang"]) >= Convert.ToInt32(newRow["tuThang"]) && Convert.ToInt32(oldRow["denThang"]) <= Convert.ToInt32(newRow["denThang"]))
                {
                    oldRow.Delete();
                    i = i - 1;
                }
            }//ket thuc xoa dong trung
        }

        /// <summary>
        /// Them cac khoang qua trinh cho qua trinh duoc lien tuc
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        /// <param name="thangkt"></param>
        private void ThemQuaTrinh(QuatrinhBHXH dsQuatrinh,string thangkt)
        {
            int i;
            DataRow oldRow = null;
            DataRow newRow = null;
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {

                if (dsQuatrinh.Tables[0].Rows[i]["loaips"].ToString() == "1")
                {
                    oldRow = dsQuatrinh.Tables[0].Rows[i];
                }
                //truong hop ngay phat sinh khong phai la thang cuoi cua qua trinh
                if (i == dsQuatrinh.Tables[0].Rows.Count - 1)
                {
                    //chi xet truong hop ps = 2
                    if (dsQuatrinh.Tables[0].Rows[i]["loaips"].ToString() == "2" && oldRow != null)
                    {
                        //them dong de lien tuc qua trinh
                        if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["denthang"]) < Convert.ToInt32(thangkt))
                        {
                            newRow = dsQuatrinh.Tables[0].NewRow();
                            newRow["Madvi"] = oldRow["Madvi"];
                            newRow["Tuthang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["denThang"]) + 1;
                            if (newRow["Tuthang"].ToString().Substring(4) == "13")
                            {
                                newRow["Tuthang"] = Convert.ToInt32(newRow["Tuthang"].ToString().Substring(0, 4)) + 1;
                                newRow["Tuthang"] = newRow["Tuthang"].ToString() + "01";
                            }
                            newRow["DenThang"] = thangkt;
                            newRow["Loaidt"] = oldRow["Loaidt"];
                            newRow["Ma_nte"] = oldRow["Ma_nte"];
                            newRow["Mucluong"] = oldRow["Mucluong"];
                            newRow["Hsl"] = oldRow["Hsl"];
                            newRow["PCCV"] = oldRow["PCCV"];
                            newRow["PCTN"] = oldRow["PCTN"];
                            newRow["PCNG"] = oldRow["PCNG"];
                            newRow["PCKV"] = oldRow["PCKV"];
                            newRow["pa"] = oldRow["pa"];
                            newRow["Congviec"] = oldRow["Congviec"];
                            newRow["Tendvi"] = oldRow["Tendvi"];
                            newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                              Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        }
                    }

                }
                else //co khoang trong giua cac qua trinh, phai lap day cac khoang trong do
                {
                    if (oldRow != null && DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(4, 2) + "/01"),
                            Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString().Substring(4, 2) + "/01")) > 1 && dsQuatrinh.Tables[0].Rows[i]["pa"].ToString().Trim() != "")
                    {
                        newRow = dsQuatrinh.Tables[0].NewRow();
                        newRow["Madvi"] = oldRow["Madvi"];
                        //tu thang = den thang cua qua trinh dang chay + 1
                        newRow["Tuthang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["denThang"]) + 1;
                        if (newRow["Tuthang"].ToString().Substring(4) == "13")
                        {
                            newRow["Tuthang"] = Convert.ToInt32(newRow["Tuthang"].ToString().Substring(0, 4)) + 1;
                            newRow["Tuthang"] = newRow["Tuthang"].ToString() + "01";
                        }
                        //den thang = tu thang cua qua trinh tiep theo - 1
                        newRow["DenThang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString()) - 1;
                        if (newRow["DenThang"].ToString().Substring(4) == "00")
                        {
                            newRow["DenThang"] = Convert.ToInt32(newRow["DenThang"].ToString().Substring(0, 4)) - 1;
                            newRow["DenThang"] = newRow["DenThang"].ToString() + "12";
                        }
                        newRow["Loaidt"] = oldRow["Loaidt"];
                        newRow["Ma_nte"] = oldRow["Ma_nte"];
                        newRow["Mucluong"] = oldRow["Mucluong"];
                        newRow["Hsl"] = oldRow["Hsl"];
                        newRow["PCCV"] = oldRow["PCCV"];
                        newRow["PCTN"] = oldRow["PCTN"];
                        newRow["PCNG"] = oldRow["PCNG"];
                        newRow["PCKV"] = oldRow["PCKV"];
                        newRow["pa"] = oldRow["pa"];
                        newRow["Congviec"] = oldRow["Congviec"];
                        newRow["Tendvi"] = oldRow["Tendvi"];
                        newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                          Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        i++;
                    }
                }
            }//ket thu them dong de hoan thanh qua trinh
        }
        private void SetTenDonVi(QuatrinhBHXH dsQuatrinh,string sobhxh,string Maxqt,int k)
        {
            int i;
            DataRow oldRow = null;
            SqlCommand command;
            string queryString;
            SqlDataReader reader;
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {
                oldRow = dsQuatrinh.Tables[0].Rows[i];
                //Truong hop dang lam viec va ma don vi = ma don vi tren luoi
                if (oldRow["Madvi"].ToString().Trim() == FlxSobhxh.Rows[k]["Madvi"].ToString().Trim() && oldRow["PA"].ToString() != "TS"
                    && oldRow["PA"].ToString() != "OF"
                    && oldRow["PA"].ToString() != "GH"
                    && oldRow["PA"].ToString() != "GD")
                {
                    oldRow["Tendvi"] = FlxSobhxh.Rows[k]["TENDVI"];
                    oldRow["DiaChi"] = FlxSobhxh.Rows[k]["DIACHI"];
                }
                else if (oldRow["Madvi"].ToString() != "HA0000A" && oldRow["PA"].ToString() != "TS"  //Truong hop dang lam viec va ma don vi != ma don vi tren luoi
                    && oldRow["PA"].ToString() != "OF"
                    && oldRow["PA"].ToString() != "GH"
                    && oldRow["PA"].ToString() != "GD")
                {
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        connection.Open();
                        command = connection.CreateCommand();
                        queryString = "select Tendvi,DiaChi from DMDONVI WHERE MADVI = '" + oldRow["Madvi"].ToString() + "'";
                        command = connection.CreateCommand();
                        command.CommandText = queryString;
                        reader = command.ExecuteReader();
                        reader.Read();
                        oldRow["Tendvi"] = reader["Tendvi"];
                        oldRow["DiaChi"] = reader["DiaChi"];
                        reader.Close();
                    }
                }
                else if (oldRow["PA"].ToString() == "TS") //Truong hop thai san
                {
                    oldRow["Congviec"] = "";
                    oldRow["Tendvi"] = "NghØ h­ëng chÕ ®é thai s¶n";
                    oldRow["Mucluong"] = 0;
                    oldRow["Hsl"] = 0;

                }
                else if (oldRow["PA"].ToString() == "OF" //truong hop nghi viec
                    || oldRow["PA"].ToString() == "GH"
                    || oldRow["PA"].ToString() == "GD")
                {
                    oldRow["Congviec"] = "";
                    oldRow["Tendvi"] = "Kh«ng tham gia";
                    oldRow["Mucluong"] = 0;
                    oldRow["Hsl"] = 0;
                }

            }
            //chen them donvi cho cac dong ko co ten don vi nam trong bang history
            queryString = "exec sp_executesql N'SELECT Madvi, Tendvi, Nghenghiep, Loaidt, Tuthang, Denthang, Dk1, Dk2, Dk3, Dk4, Dk5, Dk6 "
            + " FROM HISTORY WHERE Sobhxh=@P1  AND ((@P2  BETWEEN Tuthang AND Denthang) or "
            + " (@P3  BETWEEN Tuthang AND Denthang) OR (@P4 <=Tuthang AND @P5 >=Denthang)) ',"
            + " N'@P1 varchar(10),@P2 varchar(6),@P3 varchar(6),@P4 varchar(6),@P5 varchar(6)', '" + sobhxh + "', '196001', '" + Maxqt + "'"
            + " ,'196001', '" + Maxqt + "'";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                command = connection.CreateCommand();
                command.CommandText = queryString;
                connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
                    {
                        oldRow = dsQuatrinh.Tables[0].Rows[i];
                        //tim dong de insert tendenvi
                        if (oldRow["loaips"].ToString() == "2" && oldRow["DenThang"].ToString() == reader["Denthang"].ToString())
                        {
                            oldRow["Tendvi"] = reader["Tendvi"];
                            oldRow["DiaChi"] = "";
                        }
                        else if (oldRow["PA"].ToString() == "TS")
                        {
                            oldRow["Congviec"] = "";
                            oldRow["Tendvi"] = "NghØ h­ëng chÕ ®é thai s¶n";
                            oldRow["Mucluong"] = 0;
                            oldRow["Hsl"] = 0;
                        }
                        else if (oldRow["PA"].ToString() == "OF" || oldRow["PA"].ToString() == "GH" || oldRow["PA"].ToString() == "GD")
                        {
                            oldRow["Congviec"] = "";
                            oldRow["Tendvi"] = "Kh«ng tham gia";
                            oldRow["Mucluong"] = 0;
                            oldRow["Hsl"] = 0;
                        }
                    }
                }
                reader.Close();
            }//ket thuc chen ten don vi
        }
        /// <summary>
        /// Sap Xep Qua Trinh
        /// </summary>
        /// <param name="dsTQuatrinh"></param>
        /// <param name="thanggh"></param>
        /// <param name="Maxqt"></param>
        /// <param name="k"></param>
        /// <returns></returns>
        private QuatrinhBHXH SapXepQuaTrinh(QuatrinhBHXH dsTQuatrinh, string thanggh,string Maxqt,int k)
        {
            DataRow newRow = null;
            DataRow currentRow = null;
            QuatrinhBHXH dsQuatrinh = new QuatrinhBHXH();
            for (int j = 0; j < dsTQuatrinh.Tables[0].Rows.Count; j++)
            {
                currentRow = dsTQuatrinh.Tables[0].Rows[j];

                if (Convert.ToInt32(currentRow["Maqt"]) <= Convert.ToInt32(thanggh)) // lay nhung qua trinh nho hon thanggh
                {
                    newRow = dsQuatrinh.Tables[0].NewRow();
                    if (currentRow["loaips"].ToString() == "1") //truong hop ps ==1
                    {
                        newRow["Madvi"] = currentRow["Madvi"];
                        newRow["Tuthang"] = currentRow["Maqt"];
                        newRow["Loaidt"] = currentRow["Loaidt"];
                        newRow["Ma_nte"] = currentRow["Ma_nte"];
                        newRow["Mucluong"] = currentRow["Mucluong"];
                        newRow["Hsl"] = currentRow["Hsl"];
                        newRow["PCCV"] = currentRow["PCCV"];
                        newRow["PCTN"] = currentRow["PCTN"];
                        newRow["PCNG"] = currentRow["PCNG"];
                        newRow["PCKV"] = 0;
                        newRow["pa"] = currentRow["pa"];
                        newRow["loaips"] = currentRow["loaips"];
                        if (currentRow["Congviec"].ToString().Trim() == "")
                        {
                            newRow["Congviec"] = FlxSobhxh.Rows[k]["MACV"];
                        }
                        else
                        {
                            newRow["Congviec"] = currentRow["Congviec"];
                        }
                        //sap xep theo ma qua trinh
                        switch (newRow["pa"].ToString().Trim())
                        {
                            case "DC":
                            case "TM":
                            case "TC":
                            case "TD":
                            case "ON":
                            case "GC":
                            case "GH":
                            case "OF":
                            case "AD":
                            case "TS":
                            case "CD":
                                PA_TM_01(dsQuatrinh, newRow,Maxqt);
                                break;
                            case "GD":
                                PA_GD_01(dsQuatrinh, newRow,Maxqt);
                                break;


                        }
                                                
                    }
                    else if (currentRow["loaips"].ToString() == "2")  //loai ps=2
                    {
                        newRow["Madvi"] = currentRow["Madvi"];
                        newRow["Tuthang"] = currentRow["Tuthang"];
                        newRow["Denthang"] = currentRow["Denthang"];
                        newRow["Loaidt"] = currentRow["Loaidt"];
                        newRow["Ma_nte"] = currentRow["Ma_nte"];
                        newRow["Mucluong"] = currentRow["Mucluong"];
                        newRow["Hsl"] = currentRow["Hsl"];
                        newRow["PCCV"] = currentRow["PCCV"];
                        newRow["PCTN"] = currentRow["PCTN"];
                        newRow["PCNG"] = currentRow["PCNG"];
                        newRow["PCKV"] = currentRow["PCKV"];
                        newRow["loaips"] = currentRow["loaips"];

                        newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                        newRow["pa"] = currentRow["pa"];

                        if (currentRow["Congviec"].ToString().Trim() == "")
                        {
                            newRow["Congviec"] = FlxSobhxh.Rows[k]["MACV"];
                        }
                        else
                        {
                            newRow["Congviec"] = currentRow["Congviec"];
                        }
                        //sap xep theo ma qua trinh
                        switch (newRow["pa"].ToString().Trim())
                        {

                            case "AD":
                                PA_AD(dsQuatrinh, newRow);
                                break;
                            case "TS":
                                PA_DC(dsQuatrinh, newRow);
                                break;
                            case "CD":
                                PA_CD(dsQuatrinh, newRow);
                                break;
                            case "":
                            case "DC":
                            case "TM":
                            case "TC":
                            case "TD":
                            case "ON":
                            case "GC":
                            case "GD":
                            case "GH":
                            case "OF":
                                PA_DC(dsQuatrinh, newRow);
                                break;

                        }
                        if (newRow["Congviec"].ToString().Trim() == "")
                        {
                            newRow["Congviec"] = FlxDetail.Rows[k]["MACV"];
                        }
                    }
                }

            }
            return dsQuatrinh;
        }
        /// <summary>
        /// so sanh qua trinh tham gia bhxh voi qua trinh da co to roi de tim ra 
        /// thang bat dau tiep theo in to roi
        /// </summary>
        /// <param name="thangbdMin"></param>
        /// <param name="k"></param>
        /// <returns></returns>
        private string GetThangBatDau(string thangbdMin,string sobhxh, int k)
        {

            SqlCommand command;
            string queryString, thangbd="";
            SqlDataReader reader;

            //lay thang ket thuc trong to roi
            queryString = "exec sp_executesql N'SELECT MAX(Thangkt) AS Thangkt FROM INTR_HDR WHERE Sobhxh = @P1"
                   + " AND LoaiXN <>''CS'' AND Dacap=0 AND Thuhoi=0', N'@P1 varchar(10)', '" + sobhxh + "'";
            using (SqlConnection connection = new SqlConnection(connectionString1))
            {
                command = connection.CreateCommand();
                command.CommandText = queryString;
                connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    thangbd = reader["Thangkt"].ToString(); //set thang ket thuc trong qua trinh la thang bd
                }
                reader.Close();
            }
            if (thangbd != "") //da co in to roi, lay thang tiep theo
            {
                thangbd = Convert.ToString(Convert.ToInt32(thangbd) + 1);
                if (thangbd.ToString().Substring(4) == "13")
                {
                    thangbd = (Convert.ToInt32(thangbd.Substring(0, 4)) + 1).ToString();
                    thangbd = thangbd + "01";
                }
            }
            else // chua in to roi
            {
                //so sach min qua trinh va thang nhap tren len
                if (Convert.ToInt32(thangbdMin) > Convert.ToInt32(FlxSobhxh.Rows[k]["Tuthang"]))
                {
                    thangbd = thangbdMin;

                }
                else
                {
                    thangbd = FlxSobhxh.Rows[k]["Tuthang"].ToString(); //lay gia tri nhap tren luoi
                }
            }
            return thangbd;

        }
        /// <summary>
        /// Lay thang bat dau tham gia chuong trinh
        /// </summary>
        /// <param name="sobhxh"></param>
        /// <param name="dsTQuatrinh"></param>
        /// <param name="thangbdMin"></param>
        /// <param name="Maxqt1"></param>
        /// <returns></returns>
        private string GetQuaTrinhVaThangBatDauQuaTrinh(string sobhxh, QuatrinhBHXH dsTQuatrinh,string thangbdMin,string Maxqt1)
        {
            DataRow newRow = null;
            SqlCommand command;
            string queryString;
            SqlDataReader reader;
           
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                //lay qua trinh cua mot so bhxh
                queryString = "exec sp_executesql N'EXEC QUATRINHCN @P1 , @P2 , @P3 ', "
                    + " N'@P1 varchar(16),@P2 varchar(6),@P3 varchar(6)', '" + sobhxh + "', '190101', '" + Maxqt1 + "'";
                command = connection.CreateCommand();
                connection.Open();
                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    newRow = dsTQuatrinh.Tables[0].NewRow();
                    newRow["Madvi"] = reader["Madvi"];
                    newRow["Maqt"] = reader["Maqt"].ToString().Substring(0, 6);
                    newRow["Tuthang"] = reader["Tuthang"];
                    newRow["Denthang"] = reader["Denthang"];
                    newRow["Loaidt"] = reader["Loaidt"];
                    newRow["Ma_nte"] = reader["Ma_nte"];
                    newRow["Mucluong"] = reader["ML"];
                    newRow["Hsl"] = reader["Hsl"];
                    newRow["PCCV"] = reader["pc1"];
                    newRow["PCTN"] = reader["pc2"];
                    newRow["PCNG"] = reader["pc3"];
                    //Tu thang 12/2007 khong co pc4
                    newRow["PCKV"] = 0;
                    newRow["pa"] = reader["pa"];
                    newRow["loaips"] = reader["loaips"];
                    newRow["Congviec"] = reader["Congviec"];
                    //truong hop SB, truong hop nay chua tinh duoc
                    if (newRow["pa"].ToString() == "SB")
                    {
                        PA_SB(dsTQuatrinh, newRow);
                    }
                    else
                    {
                        dsTQuatrinh.Tables[0].Rows.Add(newRow);
                        //Tim thang bat dau cua qua trinh 
                        if (newRow["Tuthang"].ToString().Trim() == "") //khong co tu thang
                        {
                            if (Convert.ToInt32(thangbdMin) > Convert.ToInt32(newRow["Maqt"]))
                            {
                                thangbdMin = newRow["Maqt"].ToString();
                            }
                        }
                        else
                        {
                            if (Convert.ToInt32(thangbdMin) > Convert.ToInt32(newRow["Tuthang"]))
                            {
                                thangbdMin = newRow["Tuthang"].ToString();
                            }
                        }
                    }


                }
                reader.Close();
            }//ket thuc dua du lieu vao dsTQuatrinh
            return thangbdMin;
        }
        /// <summary>
        /// lay thang giam cua so bhxh
        /// </summary>
        /// <param name="k"> so thu tu cua so bhxh dang chon tren luoi</param>
        /// <returns></returns>
        private bool GetThangChotSo(int k,string sobhxh, ref string Maxqt1, ref string Maxqt)
        {
            
            if (FlxSobhxh.Rows[k]["Denthang"] != null) //Truong hop nhap thang chot so
            {
                if (CheckThangChotSo(sobhxh, FlxSobhxh.Rows[k]["denthang"].ToString()))
                {
                    Maxqt1 = TangThang(FlxSobhxh.Rows[k]["denthang"].ToString());
                    Maxqt = FlxSobhxh.Rows[k]["denthang"].ToString();
                }
                else
                {
                    MessageBox.Show("Sè bhxh " + sobhxh + " ch­a chèt gi¶m");
                    return false;
                }
            }
            else //Khong nhap thang chot so, Tim Thang giam
            {
                Maxqt1 = TimThangGiam(sobhxh);
                if (Maxqt1 == "")
                {
                    MessageBox.Show("Sè bhxh " + sobhxh + " ch­a chèt gi¶m");
                    return false;
                }
                //custom maxqt giam di mot thang
                Maxqt = GiamThang(Maxqt1);
            }
            return true;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="k"></param>
        /// <param name="sobhxh"></param>
        /// <param name="Maxqt1"></param>
        /// <param name="Maxqt"></param>
        /// <returns></returns>
        private bool GetThangHangNam(int k, string sobhxh, ref string Maxqt1, ref string Maxqt)
        {
                bool flag=true; // biet duoc so so co giam truoc thoi han in to roi hang nam
                Maxqt1 = TimThangGiam(sobhxh);
                if (Maxqt1 == "") //so bhxh chua giam
                {
                    Maxqt1 = TangThang(FlxSobhxh.Rows[k]["denthang"].ToString());
                    Maxqt = FlxSobhxh.Rows[k]["denthang"].ToString();
                    flag = false;
                }
                else //so bhxh da giam, kiem tra thoi gian co lon hon ko thoi gian in hang nam ko
                {
                    Maxqt = GiamThang(Maxqt1);
                    if (Convert.ToInt32(Maxqt) > Convert.ToInt32(FlxSobhxh.Rows[k]["denthang"]))
                    {
                        Maxqt1 = TangThang(FlxSobhxh.Rows[k]["denthang"].ToString());
                        Maxqt = FlxSobhxh.Rows[k]["denthang"].ToString();
                        flag = false;
                    }
                }
                return flag;
            
        }
        /// <summary>
        /// Get thang chot so
        /// </summary>
        /// <param name="sobhxh"></param>
        /// <param name="thanggiam"></param>
        /// <returns></returns>
        private Boolean CheckThangChotSo(string sobhxh,string thanggiam)
        {
            string queryString;
            SqlCommand command;
            SqlDataReader reader;
            queryString = "select a.tuthang as tuthang,PA, thangkt from MISBHXH_NT.dbo.HSC47_DTL a left join"
            + " (SELECT max(thangkt) as thangkt,sobhxh  FROM MISBHXH_SOTHE_NT.dbo.INTR_HDR "
            + " group by sobhxh) b on a.sobhxh = b.sobhxh"
            + " where  a.sobhxh =  '" + sobhxh + "' and PA in ('GH','GD') and tuthang = '" + TangThang(thanggiam) + "'"
            + " order by maqt,a.tuthang";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                command = connection.CreateCommand();
                command.CommandText = queryString;
                connection.Open();
                reader = command.ExecuteReader();
                if (reader.HasRows == false) {
                    MessageBox.Show("Sè bhxh " + sobhxh + " kh«ng ®ung th¸ng chèt sæ");
                    return false; 
                }
            }
            return true;
        }
        /// <summary>
        /// Lay Thang Giam Tham Gia trong qua Trinh
        /// </summary>
        /// <returns></returns>
        private string TimThangGiam(string sobhxh)
        {
            string queryString;
            SqlCommand command;
            SqlDataReader reader;
            string Maxqt = "";
            //tim thang giam tham gia bhxh
            queryString = "select a.tuthang as tuthang,PA, thangkt from MISBHXH_NT.dbo.HSC47_DTL a left join"
            + " (SELECT max(thangkt) as thangkt,sobhxh  FROM MISBHXH_SOTHE_NT.dbo.INTR_HDR "
            + " group by sobhxh) b on a.sobhxh = b.sobhxh"
            + " where  a.sobhxh =  '" + sobhxh + "'"
            + " order by maqt,a.tuthang";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                command = connection.CreateCommand();
                command.CommandText = queryString;
                connection.Open();
                reader = command.ExecuteReader();
                if (reader.HasRows == false) { return ""; }
                while (reader.Read())
                {
                    //KIEM TRA PHUONG AN SB KHONG LAM
                    if (reader["pa"].ToString() == "SB")
                    {
                        MessageBox.Show("số bhxh " + sobhxh.Trim() + " có Phương án " + reader["pa"].ToString() + " chưa thực hiện được ");
                        return "";
                    }

                    if (reader["thangkt"].ToString() == "") //chua co to roi nao duoc in ra
                    {
                        if (Maxqt == "" && (reader["pa"].ToString() == "GH" || reader["pa"].ToString() == "GD"))
                        {
                            Maxqt = reader["tuthang"].ToString();
                        }
                        else if (Maxqt != "" && (reader["pa"].ToString() == "DC" || reader["pa"].ToString() == "AD" || reader["pa"].ToString() == "TM" || reader["pa"].ToString() == "ON"))
                        {
                            Maxqt = "";
                        }
                    }
                    else//da co to roi,  so sanh voi thoi gian in to roi de lay maxqt
                    {

                        if (Maxqt == "" && (reader["pa"].ToString() == "GH" || reader["pa"].ToString() == "GD") &&
                            Convert.ToInt32(reader["tuthang"]) - 1 > Convert.ToInt32(reader["thangkt"]))
                        {
                            Maxqt = reader["tuthang"].ToString();
                        }
                        else if (Maxqt != "" && (reader["pa"].ToString() == "DC" || reader["pa"].ToString() == "AD" || reader["pa"].ToString() == "TM" || reader["pa"].ToString() == "ON"))
                        {
                            Maxqt = "";
                        }
                    }
                }
                reader.Close();

                if (Maxqt == "")
                {
                    return "";
                }
                
            }
            return Maxqt;
        }
        /// <summary>
        /// Tang mot thang
        /// </summary>
        /// <param name="thanggiam"></param>
        /// <returns></returns>
        private string TangThang(string thanggiam)
        {
            thanggiam = Convert.ToString(Convert.ToInt32(thanggiam) + 1);
            if (thanggiam.Substring(4) == "13")
            {
                thanggiam = Convert.ToString(Convert.ToInt32(thanggiam.Substring(0, 4)) + 1);
                thanggiam = thanggiam + "01";
            }
            return thanggiam;
        }
        /// <summary>
        /// Giam di mot thang
        /// </summary>
        /// <param name="thanggiam"></param>
        /// <returns></returns>
        private string GiamThang(string thanggiam)
        {
            thanggiam = Convert.ToString(Convert.ToInt32(thanggiam) - 1);
            if (thanggiam.Substring(4) == "00")
            {
                thanggiam = Convert.ToString(Convert.ToInt32(thanggiam.Substring(0, 4)) - 1);
                thanggiam = thanggiam + "12";
            }
            return thanggiam;
        }

        /// <summary>
        /// kiem tra so luong to roi con du de xuat ko
        /// </summary>
        /// <param name="soluong"></param>
        /// <returns></returns>
        private int CheckSoLuongToRoi(int soluong)
        {
            string strMonth;
            int intSonhap=0, intSoxuat=0;
            strMonth = Convert.ToString(Convert.ToInt32(ModuleBHXH.GetMonth())-1);
            if (strMonth.Substring(4) == "00")
            {
                strMonth = Convert.ToString(Convert.ToInt32(strMonth.Substring(0, 4)) - 1);
                strMonth = strMonth + "12";
            }
            SqlDataReader reader;
            using (SqlConnection connection =
              new SqlConnection(connectionString1))
            {
                string queryString;
                queryString = " exec sp_executesql N'SELECT SPACE(6) As Thang, Makho, Mavt, Cuoiky As Dauky, Cuoiky*0 As Nhap, Cuoiky*0 As Xuat, "
                + " Cuoiky, Ma_Quan, SPACE(1) As Loai  FROM SODUVT "
                + " WHERE Thang = @P1  AND Ma_Quan=@P2  AND Makho = @P3  AND Mavt = @P4 ', "
                + " N'@P1 varchar(6),@P2 varchar(2),@P3 varchar(10),@P4 varchar(2)', '" + strMonth + "', '01', 'QLS       ', 'RT'";
                               
                SqlCommand command = connection.CreateCommand();
                command.CommandText = queryString;
                connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    intSonhap = Convert.ToInt32(reader["Cuoiky"]);
                }
                reader.Close();
                queryString = " exec sp_executesql N'SELECT b.Makho, b.Mavt, a.NX,  SUM(CASE WHEN a.NX=''N'' THEN b.Soluong ELSE 0 END) As Nhap,"
                + " SUM(CASE WHEN a.NX=''X'' THEN b.Soluong ELSE 0 END) As Xuat  FROM CTUVT_HDR a, "
                + " CTUVT_DTL b WHERE a.Keysl=b.Keysl  AND a.Ngayct BETWEEN @P1  AND @P2   AND b.Makho = @P3  "
                + " AND b.Mavt = @P4  GROUP BY b.Makho, b.Mavt, a.NX ', N'@P1 datetime,@P2 datetime,@P3 varchar(10),@P4 varchar(2)', "
                + " '" + ModuleBHXH.strMonths.Substring(4, 2) + "/01/" + ModuleBHXH.strMonths.Substring(0, 4) + "', '" + ModuleBHXH.strDate + "', 'QLS       ', 'RT'";

                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    intSonhap = intSonhap + Convert.ToInt32(reader["Nhap"]);
                    intSoxuat = intSoxuat + Convert.ToInt32(reader["Xuat"]);
                }
                reader.Close();
                queryString = " exec sp_executesql N'SELECT b.Manv As Makho, b.Mavt, ''N'' As NX,  SUM(b.Soluong) As Nhap  "
                + " FROM CTUVT_HDR a, CTUVT_DTL b WHERE a.Keysl=b.Keysl  AND a.Ngayct BETWEEN @P1  AND @P2   "
                + " AND a.NX=''X'' AND b.Manv<>''''  AND b.Manv = @P3  AND b.Mavt = @P4  GROUP BY b.Manv, b.Mavt ', "
                + " N'@P1 datetime,@P2 datetime,@P3 varchar(10),@P4 varchar(2)', "
                + "'" + ModuleBHXH.strMonths.Substring(4, 2) + "/01/" + ModuleBHXH.strMonths.Substring(0, 4) + "', '" + ModuleBHXH.strDate + "', 'QLS       ', 'RT'";
                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    intSonhap = intSonhap + Convert.ToInt32(reader["Nhap"]);
                }
                reader.Close();
                queryString = " exec sp_executesql N'SELECT Makho, Mavt, NX,  SUM(CASE WHEN NX=''N'' THEN Soluong ELSE 0 END) As Nhap,"
                + " SUM(CASE WHEN NX=''X'' THEN Soluong ELSE 0 END) As Xuat  FROM CTUVT_SD "
                + " WHERE Ngayct BETWEEN @P1  AND @P2   AND Makho = @P3  AND Mavt = @P4  GROUP BY Makho, Mavt, NX ', "
                + " N'@P1 datetime,@P2 datetime,@P3 varchar(10),@P4 varchar(2)', "
                + "'" + ModuleBHXH.strMonths.Substring(4, 2) + "/01/" + ModuleBHXH.strMonths.Substring(0, 4) + "', '" + ModuleBHXH.strDate + "', 'QLS       ', 'RT'";
                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    intSonhap = intSonhap + Convert.ToInt32(reader["Nhap"]);
                    intSoxuat = intSoxuat + Convert.ToInt32(reader["Xuat"]);
                }
                reader.Close();
                queryString = " exec sp_executesql N'SELECT Makho, ''RT'' As Mavt, ''X'' As NX,  SUM(Soluong) As Xuat  "
                + " FROM CTUVT_SD WHERE Ngayct BETWEEN @P1  AND @P2  AND NX=''N'' AND (Mavt=''RH'' OR Mavt=''RB'') AND Makho = @P3  GROUP BY Makho ', "
                + " N'@P1 datetime,@P2 datetime,@P3 varchar(10)', "
                + "'" + ModuleBHXH.strMonths.Substring(4, 2) + "/01/" + ModuleBHXH.strMonths.Substring(0, 4) + "', '" + ModuleBHXH.strDate + "', 'QLS       '";
                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    intSoxuat = intSoxuat + Convert.ToInt32(reader["Xuat"]);
                }
                reader.Close();
            }
            return intSonhap - intSoxuat;
        }
        /// <summary>
        /// lay thong tin chi tiet cho tung dong qua tring tu so bhxh va thangbd cua dong qua trinh
        /// </summary>
        /// <param name="sobhxh"></param>
        /// <param name="thangbd"></param>
        private void GetRow(string sobhxh, string thangbd)
        {
            DataRow[] foundRows;
            int i = 1;
            faQuaTrinh.Rows.Count = 1;
            //thangbd = ModuleBHXH.FormatThangNam(thangbd);
            foundRows = dsKQuatrinh.Tables[0].Select("Sobhxh = '" + sobhxh.ToString().Trim() + "' and maqt = '" + thangbd + "'", "TLBHXH,Tuthang");
            
            //IEnumerable<DataRow> query =
            //foundRows.OrderBy(quatrinh => quatrinh.Field<string>("Tuthang"));


            foreach (DataRow foundRow in foundRows)
            {
                
                faQuaTrinh.Rows.Count = faQuaTrinh.Rows.Count + 1;
                faQuaTrinh.Rows[i]["Madvi"] = foundRow["Madvi"];
                faQuaTrinh.Rows[i]["TuThang"] = foundRow["Tuthang"].ToString();
                faQuaTrinh.Rows[i]["DenThang"] = foundRow["DenThang"].ToString();
                faQuaTrinh.Rows[i]["Loai"] = foundRow["Loaidt"];
                faQuaTrinh.Rows[i]["LoaiTT"] = foundRow["Ma_nte"];
                faQuaTrinh.Rows[i]["pa"] = foundRow["pa"];


                if (Convert.ToDouble(foundRow["MUCLUONG"]) != 0) { faQuaTrinh.Rows[i]["MUCLUONG"] = foundRow["MUCLUONG"]; }
                if (Convert.ToDouble(foundRow["HSL"]) != 0) { faQuaTrinh.Rows[i]["HSL"] = foundRow["HSL"]; }
                if (Convert.ToDouble(foundRow["PCCV"]) != 0) { faQuaTrinh.Rows[i]["PCCV"] = foundRow["PCCV"]; }
                if (Convert.ToDouble(foundRow["PCTN"]) != 0) { faQuaTrinh.Rows[i]["PCTN"] = foundRow["PCTN"]; }
                if (Convert.ToDouble(foundRow["PCNG"]) != 0) { faQuaTrinh.Rows[i]["PCNG"] = foundRow["PCNG"]; }
                // if (Convert.ToDouble(foundRow["PCKV"]) != 0) { faQuaTrinh.Rows[i]["PCKV"] = foundRow["pc4"]; }

                faQuaTrinh.Rows[i]["Congviec"] = foundRow["Congviec"];

                i++;
            }

        }
        /// <summary>
        /// dua du lien vao luoi FlxDetail sau khi da kiem tra xong
        /// </summary>
        /// <param name="k"></param>
        /// <param name="thangbd"></param>
        /// <param name="thangkt"></param>
        /// <param name="xacnhan"></param>
        /// <param name="nam"></param>
        /// <param name="thang"></param>
        /// <param name="tuthangxn"></param>
        private void GetDataOnFlex(int k,string thangbd, string thangkt,string xacnhan,
            int nam,int thang,string tuthangxn)
        {
            int i;
            FlxDetail.Rows.Count = FlxDetail.Rows.Count + 1;
            FlxDetail.Rows[FlxDetail.Rows.Count-1]["CHECK"] = 1;
            FlxDetail.Rows[FlxDetail.Rows.Count-1]["STT"] = FlxDetail.Rows.Count;
            FlxDetail.Rows[FlxDetail.Rows.Count-1]["Madvi"] = FlxSobhxh.Rows[k]["Madvi"];
            FlxDetail.Rows[FlxDetail.Rows.Count-1]["Sobhxh"] = FlxSobhxh.Rows[k]["Sobhxh"];
            FlxDetail.Rows[FlxDetail.Rows.Count-1]["Ho"] = FlxSobhxh.Rows[k]["Ho"];
            FlxDetail.Rows[FlxDetail.Rows.Count-1]["Ten"] = FlxSobhxh.Rows[k]["Ten"];

            FlxDetail.Rows[FlxDetail.Rows.Count-1]["tuthang"] = thangbd;
            FlxDetail.Rows[FlxDetail.Rows.Count-1]["denthang"] = thangkt;

            for (i = 1; i < FlxDetail.Rows.Count-1; i++)
            {
                if (FlxSobhxh.Rows[k]["Madvi"].ToString() == FlxDetail.Rows[i]["Madvi"].ToString())
                {
                    FlxDetail.Rows[FlxDetail.Rows.Count - 1]["dongden"] = FlxDetail.Rows[i]["dongden"].ToString();
                    break;
                }
            }
            if (i == FlxDetail.Rows.Count-1)
            {
                FlxDetail.Rows[FlxDetail.Rows.Count - 1]["dongden"] = GetThangDongTien(FlxSobhxh.Rows[k]["Madvi"].ToString(), FlxSobhxh.Rows[k]["Sobhxh"].ToString());
            }
            FlxDetail.Rows[FlxDetail.Rows.Count - 1]["xacnhan"] = xacnhan;
            FlxDetail.Rows[FlxDetail.Rows.Count-1]["tuthangxn"] = tuthangxn;
            if (xacnhan == FlxSobhxh.Rows[k]["xacnhan"].ToString() && xacnhan != "")
            {
                FlxDetail.Rows[FlxDetail.Rows.Count - 1]["denthangxn"] = thangkt;
            }
            FlxDetail.Rows[FlxDetail.Rows.Count - 1]["sonam"] = nam;
            FlxDetail.Rows[FlxDetail.Rows.Count - 1]["sothang"] = thang;


            FlxDetail.Rows[FlxDetail.Rows.Count-1]["tuthangxntn"] = "";
            FlxDetail.Rows[FlxDetail.Rows.Count-1]["denthangxntn"] = "";
            FlxDetail.Rows[FlxDetail.Rows.Count-1]["sonamtn"] = 0;
            FlxDetail.Rows[FlxDetail.Rows.Count-1]["sothangtn"] =0;

            //in to roi hang nam
            if (xacnhan == "") { 
                FlxDetail.Rows[FlxDetail.Rows.Count - 1]["DTDONVI"] = thangkt; 
                
                if((Convert.ToInt32(thangkt) - Convert.ToInt32(thangbd)) < 11 &&
                    FlxSobhxh.Rows[k]["Sobhxh"].ToString().Substring(0, 6) != "560962" &&
                    FlxSobhxh.Rows[k]["Sobhxh"].ToString().Substring(0, 6) != "561062" &&
                    FlxSobhxh.Rows[k]["Sobhxh"].ToString().Substring(0,6) != "561162")
                {
                    FlxDetail.Rows[FlxDetail.Rows.Count - 1]["CHECK"] = 0;
                }
            }

            CheckKhongThamGia(FlxSobhxh.Rows[k]["Sobhxh"].ToString(), thangbd, FlxDetail.Rows.Count - 1);

            
        }
        /// <summary>
        /// dua du lieu bhxh that nghiep vao luoi FlxDetail sau khi da kiem tra xong
        /// </summary>
        /// <param name="xacnhan"></param>
        /// <param name="namtn"></param>
        /// <param name="thangtn"></param>
        /// <param name="tuthangxntn"></param>
        /// <param name="denthangxntn"></param>
        private void GetDataBHTNOnFlex(string xacnhan,
          int namtn, int thangtn, string tuthangxntn, string denthangxntn)
        {
            FlxDetail.Rows[FlxDetail.Rows.Count - 1]["tuthangxntn"] = tuthangxntn;
            FlxDetail.Rows[FlxDetail.Rows.Count - 1]["denthangxntn"] = denthangxntn;
            FlxDetail.Rows[FlxDetail.Rows.Count - 1]["sonamtn"] = namtn;
            FlxDetail.Rows[FlxDetail.Rows.Count - 1]["sothangtn"] = thangtn ;
        }
        /// <summary>
        /// kiem tra dong qua trinh co phat sinh dieu chinh ko dieu danh dau do
        /// </summary>
        private void CheckDieuChinh()
        {
            string queryString;
            SqlDataReader reader;
            using (SqlConnection connection =
               new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                connection.Open();
                for (int i = 1; i < FlxDetail.Rows.Count; i++)
                {
                    queryString = "exec sp_executesql N'SELECT Sobhxh, Madvi, Maqt, Loaidt, Ma_Nte, Pa, Tuthang, Denthang, Congviec, ML_DK, HSL_DK,"
                       + " PC1_DK, PC2_DK, PC3_DK, ML, HSL, PC1, PC2, PC3,  Tyle_BHXH, Tyle_BHTN, SPACE(50) As Phucap, 100.000 * 0 As HSTN, "
                       + " 100.000 * 0 As HSNG, SPACE(250) AS Noidung, ''DC'' AS SX FROM HSC47_DTL  WHERE Sobhxh=@P1  AND Madvi=@P2  "
                       + " AND ((LEFT(Maqt,6) BETWEEN @P3  AND @P4  AND Tuthang < @P5 )  OR (LEFT(Maqt,6) = @P6  AND Tuthang < @P7  AND"
                       + " (SELECT TOP 1 Hsl+Pc1+Pc2+Pc3+Pc4+Pc5+Ml+Mlyt As ML FROM HSC47_DTL  WHERE Sobhxh=@P8  "
                       + " AND Madvi=@P9  AND LEFT(Maqt,6)=Denthang AND LEFT(Maqt,6)=@P10   AND CHARINDEX(Pa,''TT/TU/TN/GN/DN/CD'')=0 "
                       + " ORDER BY Maqt DESC)=0))  AND ((LoaiDT=''HS'' AND ((HSL_DK+PC1_DK+PC2_DK+PC3_DK+HSL+PC1+PC2+PC3 <> 0 AND "
                       + " (HSL_DK<>HSL OR PC1_DK<>PC1 OR PC2_DK<>PC2 OR PC3_DK<>PC3) ) OR (HSL_DK+PC1_DK+PC2_DK+PC3_DK+HSL+PC1+PC2+PC3 =0 "
                       + " AND CHARINDEX(Pa,''GH/OF/TS'')<>0)))  OR (Loaidt=''ML'' AND ((ML_DK+ML <> 0 AND ML_DK <> ML) OR (ML_DK+ML =0 AND "
                       + " CHARINDEX(Pa,''GH/OF/TS'')<>0))) OR Pa=''CD'') AND CHARINDEX(Pa,''TT/TU'')=0  ORDER BY Maqt, Tuthang, Denthang ', "
                       + " N'@P1 varchar(16),@P2 varchar(7),@P3 varchar(6),@P4 varchar(6),@P5 varchar(6),@P6 varchar(6),@P7 varchar(6),"
                       + " @P8 varchar(16),@P9 varchar(7),@P10 varchar(6)', '" + FlxDetail.Rows[i]["Sobhxh"].ToString() + "', '" + FlxDetail.Rows[i]["Madvi"].ToString() + "', '" + FlxDetail.Rows[i]["tuthang"].ToString() + "',"
                       + " '" + FlxDetail.Rows[i]["Denthang"].ToString() + "', '" + FlxDetail.Rows[i]["Tuthang"].ToString() + "',"
                       + " '" + Convert.ToInt16(FlxDetail.Rows[i]["Tuthang"].ToString().Substring(0, 4) + 1).ToString() + "01" + "', '" + FlxDetail.Rows[i]["Tuthang"].ToString() + "', '" + FlxDetail.Rows[i]["Sobhxh"].ToString() + "',"
                       + "'" + FlxDetail.Rows[i]["Madvi"].ToString() + "', '" + Convert.ToInt16(FlxDetail.Rows[i]["Tuthang"].ToString().Substring(0, 4) + 1).ToString() + "01" + "'";
                    command.CommandText = queryString;
                    reader = command.ExecuteReader();
                    if (reader.HasRows == true)
                    {
                        C1.Win.C1FlexGrid.CellStyle rs = this.FlxDetail.Styles.Add("rowcolor");
                        rs.ForeColor = Color.Red;
                        FlxDetail.Rows[i].Style = rs;
                    }
                    reader.Close();
                }

            }
        }
        /// <summary>
        /// them phan dieu chinh bhxh
        /// </summary>
        /// <param name="i"></param>
        /// <param name="dsIntoroi"></param>
        private void DieuChinhBHXH(int i, InToRoi dsIntoroi)
        {

            DataRow newRow = null;
            SqlDataReader reader;
            double dbML, dbHSL, dbPC1, dbPC2 = 0,dbPC3=0;
            String queryString;
            using (SqlConnection connection =
            new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                connection.Open();

                queryString = "exec sp_executesql N'SELECT Sobhxh, Madvi, Maqt, Loaidt, Ma_Nte, Pa, Tuthang, Denthang, Congviec, ML_DK, HSL_DK,"
                + " PC1_DK, PC2_DK, PC3_DK, ML, HSL, PC1, PC2, PC3,  Tyle_BHXH, Tyle_BHTN, SPACE(50) As Phucap, 100.000 * 0 As HSTN, "
                + " 100.000 * 0 As HSNG, SPACE(250) AS Noidung, ''DC'' AS SX FROM MISBHXH_NT.dbo.HSC47_DTL  WHERE Sobhxh=@P1  AND Madvi=@P2  "
                + " AND ((LEFT(Maqt,6) BETWEEN @P3  AND @P4  AND Tuthang < @P5 )  OR (LEFT(Maqt,6) = @P6  AND Tuthang < @P7  AND"
                + " (SELECT TOP 1 Hsl+Pc1+Pc2+Pc3+Pc4+Pc5+Ml+Mlyt As ML FROM MISBHXH_NT.dbo.HSC47_DTL  WHERE Sobhxh=@P8  "
                + " AND Madvi=@P9  AND LEFT(Maqt,6)=Denthang AND LEFT(Maqt,6)=@P10   AND CHARINDEX(Pa,''TT/TU/TN/GN/DN/CD'')=0 "
                + " ORDER BY Maqt DESC)=0))  AND ((LoaiDT=''HS'' AND ((HSL_DK+PC1_DK+PC2_DK+PC3_DK+HSL+PC1+PC2+PC3 <> 0 AND "
                + " (HSL_DK<>HSL OR PC1_DK<>PC1 OR PC2_DK<>PC2 OR PC3_DK<>PC3) ) OR (HSL_DK+PC1_DK+PC2_DK+PC3_DK+HSL+PC1+PC2+PC3 =0 "
                + " AND CHARINDEX(Pa,''GH/OF/TS'')<>0)))  OR (Loaidt=''ML'' AND ((ML_DK+ML <> 0 AND ML_DK <> ML) OR (ML_DK+ML =0 AND "
                + " CHARINDEX(Pa,''GH/OF/TS'')<>0))) OR Pa=''CD'') AND CHARINDEX(Pa,''TT/TU'')=0 AND Tyle_BHXH > 0  ORDER BY Maqt, Tuthang, Denthang ', "
                + " N'@P1 varchar(16),@P2 varchar(7),@P3 varchar(6),@P4 varchar(6),@P5 varchar(6),@P6 varchar(6),@P7 varchar(6),"
                + " @P8 varchar(16),@P9 varchar(7),@P10 varchar(6)', '" + FlxDetail.Rows[i]["Sobhxh"].ToString() + "', '" + FlxDetail.Rows[i]["Madvi"].ToString() + "', '" + FlxDetail.Rows[i]["tuthang"].ToString() + "',"
                + " '" + FlxDetail.Rows[i]["Denthang"].ToString() + "', '" + FlxDetail.Rows[i]["Tuthang"].ToString() + "',"
                + " '" + (Convert.ToInt16(FlxDetail.Rows[i]["Tuthang"].ToString().Substring(0, 4)) + 1).ToString() + "01" + "', '" + FlxDetail.Rows[i]["Tuthang"].ToString() + "', '" + FlxDetail.Rows[i]["Sobhxh"].ToString() + "',"
                + "'" + FlxDetail.Rows[i]["Madvi"].ToString() + "', '" + (Convert.ToInt16(FlxDetail.Rows[i]["Tuthang"].ToString().Substring(0, 4)) + 1).ToString() + "01" + "'";
                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    //chi lay nhung dieu chinh lon hon nam 200901
                    if ((Convert.ToInt32(reader["DENTHANG"]) >= 200901 && Convert.ToInt32((Convert.ToInt32(FlxDetail.Rows[i]["Tuthang"].ToString().Substring(0, 4)) - 1).ToString() + "12") >= 200901))
                    {
                        newRow = dsIntoroi.Tables[0].NewRow();
                        newRow["KEYSL"] = FlxDetail.Rows[i]["KEYSL"];
                        newRow["SOBHXH"] = FlxDetail.Rows[i]["SOBHXH"];
                        newRow["HOTEN"] = FlxDetail.Rows[i]["HO"].ToString().Trim() + " " + FlxDetail.Rows[i]["TEN"].ToString().Trim();
                        newRow["TUTHANG"] = ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["TUTHANG"].ToString());
                        newRow["DENTHANG"] = ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["DENTHANG"].ToString());
                        newRow["LOAIXN"] = FlxDetail.Rows[i]["XACNHAN"].ToString();
                        newRow["TTCHITIET"] = ModuleBHXH.FormatThangNam(reader["TUTHANG"].ToString());
                        if (Convert.ToInt32(reader["DENTHANG"]) >= Convert.ToInt32(FlxDetail.Rows[i]["Tuthang"]))
                        {
                            newRow["DTCHITIET"] = ModuleBHXH.FormatThangNam((Convert.ToInt16(FlxDetail.Rows[i]["Tuthang"].ToString().Substring(0, 4)) - 1).ToString() + "12");
                        }
                        else
                        {
                            newRow["DTCHITIET"] = ModuleBHXH.FormatThangNam(reader["DENTHANG"].ToString());
                        }
                        if (FlxDetail.Rows[i]["XACNHAN"].ToString() == "QT")
                        {
                            newRow["TTDT"] = "Tõ Th¸ng " + newRow["TUTHANG"].ToString() + " §Õn Th¸ng " + newRow["DENTHANG"];
                        }
                        else if (FlxDetail.Rows[i]["XACNHAN"].ToString().Trim() == "")
                        {
                            newRow["TTDT"] = "N¨m : " + FlxDetail.Rows[i]["denthang"].ToString().Substring(0, 4);
                        }
                        else
                        {
                            newRow["TTDT"] = "N¨m : " + FlxDetail.Rows[i]["denthangxn"].ToString().Substring(0, 4);
                        }
                        dbML = Convert.ToDouble(reader["ML"]) - Convert.ToDouble(reader["ML_DK"]);
                        dbHSL = Convert.ToDouble(reader["HSL"]) - Convert.ToDouble(reader["HSL_DK"]);
                        dbPC1 = Convert.ToDouble(reader["PC1"]) - Convert.ToDouble(reader["PC1_DK"]);
                        //truong hop tham nien vuot khung
                        if (Convert.ToDouble(reader["HSL"]) > 0 && Convert.ToDouble(reader["HSL_DK"]) > 0)
                        {
                            dbPC2 = Convert.ToInt16(Convert.ToDouble(reader["PC2"]) * 100 / Convert.ToDouble(reader["HSL"])) -
                                Convert.ToInt16(Convert.ToDouble(reader["PC2_DK"]) * 100 / Convert.ToDouble(reader["HSL_DK"]));
                        }
                        else if (Convert.ToDouble(reader["HSL"]) > 0)
                        {
                            dbPC2 = Convert.ToInt16(Convert.ToDouble(reader["PC2"]) * 100 / Convert.ToDouble(reader["HSL"]));
                        }
                        else if (Convert.ToDouble(reader["HSL_DK"]) > 0)
                        {
                            dbPC2 = -Convert.ToInt16(Convert.ToDouble(reader["PC2_DK"]) * 100 / Convert.ToDouble(reader["HSL_DK"]));
                        }
                        //PC03(THAM NIEN NGHE)
                        if (Convert.ToDouble(reader["HSL"]) > 0 && Convert.ToDouble(reader["HSL_DK"]) > 0)
                        {
                            dbPC3 = Convert.ToInt16(Convert.ToDouble(reader["PC3"]) * 100 / (Convert.ToDouble(reader["HSL"]) + Convert.ToDouble(reader["PC1"]) + +Convert.ToDouble(reader["PC2"]))) -
                                Convert.ToInt16(Convert.ToDouble(reader["PC3_DK"]) * 100 / (Convert.ToDouble(reader["HSL_DK"]) + Convert.ToDouble(reader["PC1_DK"]) + +Convert.ToDouble(reader["PC2_DK"])));
                        }
                        else if (Convert.ToDouble(reader["HSL"]) > 0)
                        {
                            dbPC3 = Convert.ToInt16(Convert.ToDouble(reader["PC3"]) * 100 / (Convert.ToDouble(reader["HSL"]) + Convert.ToDouble(reader["PC1"]) + +Convert.ToDouble(reader["PC2"])));
                        }
                        else if (Convert.ToDouble(reader["HSL_DK"]) > 0)
                        {
                            dbPC3 = -Convert.ToInt16(Convert.ToDouble(reader["PC3_DK"]) * 100 / (Convert.ToDouble(reader["HSL_DK"]) + Convert.ToDouble(reader["PC1_DK"]) + +Convert.ToDouble(reader["PC2_DK"])));
                        }
                        //truong hop ML
                        if (dbML != 0)
                        {
                            newRow["ML"] = string.Format("{0:###,##.###}", Math.Abs(dbML));
                            //CONG NOI THOI GIAN BHXH
                            if (dbML == Convert.ToDouble(reader["ML"]))
                            {
                                newRow["NOIDUNG"] = "§iÒu chØnh céng nèi thêi gian tham gia. ";
                            }
                            //dieu chinh chenh lech tang bhxh
                            else if (dbML > 0)
                            {
                                newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch t¨ng. ";
                            }
                            //dieu chinh chenh lech giam bhxh
                            else if (dbML < 0)
                            {
                                if (reader["PA"].ToString() == "TS")
                                {
                                    newRow["ML"] = "";
                                    newRow["NOIDUNG"] = "§iÒu chØnh thêi gian nghØ h­ëng chÕ ®é th¸i s¶n. ";
                                }
                                else
                                {
                                    newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch gi¶m. ";
                                }
                            }
                            newRow["NOIDUNG"] = newRow["NOIDUNG"] + ModuleBHXH.ChangeToCamel(FlxDetail.Rows[i]["Tendvi"].ToString());
                            newRow["TLBHXH"] = string.Format("{0:##}", reader["Tyle_BHXH"]) + "%";
                            dsIntoroi.Tables[0].Rows.Add(newRow);
                        }
                        // TRUONG HOP HSL
                        else if (dbHSL != 0)
                        {
                            newRow["ML"] = string.Format("{0:###,#0.000}", Math.Abs(dbHSL));
                            //CONG NOI THOI GIAN BHXH
                            if (dbHSL == Convert.ToDouble(reader["HSL"]))
                            {
                                newRow["NOIDUNG"] = "§iÒu chØnh céng nèi thêi gian tham gia. ";
                                // ghep thep pc1 và pc2 va pc3
                                if (dbPC1 != 0)
                                {
                                    newRow["LOAIPC"] = "CV";
                                    newRow["MUCPC"] = String.Format("{0:0.00}", Math.Abs(dbPC1));
                                    if (dbPC2 != 0)
                                    {
                                        newRow["LOAIPC"] = Environment.NewLine + "TV";
                                        newRow["MUCPC"] = Environment.NewLine + Math.Abs(dbPC2).ToString() + "%";
                                    }
                                    if (dbPC3 != 0)
                                    {
                                        newRow["LOAIPC"] = Environment.NewLine + "TN";
                                        newRow["MUCPC"] = Environment.NewLine + Math.Abs(dbPC3).ToString() + "%";
                                    }
                                }
                                else if (dbPC2 != 0)
                                {

                                    newRow["LOAIPC"] = "TV";
                                    newRow["MUCPC"] = Math.Abs(dbPC2).ToString() + "%";
                                    if (dbPC3 != 0)
                                    {
                                        newRow["LOAIPC"] = Environment.NewLine + "TN";
                                        newRow["MUCPC"] = Environment.NewLine + Math.Abs(dbPC3).ToString() + "%";
                                    }
                                }
                                else if (dbPC3 != 0)
                                {
                                    newRow["LOAIPC"] = "TN";
                                    newRow["MUCPC"] = Math.Abs(dbPC3).ToString() + "%";
                                }

                            }
                            //dieu chinh chenh lech tang bhxh
                            else if (dbHSL > 0)
                            {
                                newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch t¨ng. ";
                            }
                            //dieu chinh chenh lech giam bhxh
                            else if (dbHSL < 0)
                            {
                                if (reader["PA"].ToString() == "TS")
                                {
                                    newRow["ML"] = "";
                                    newRow["NOIDUNG"] = "§iÒu chØnh thêi gian nghØ h­ëng chÕ ®é thai s¶n. ";
                                }
                                else
                                {
                                    newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch gi¶m. ";
                                }

                            }
                            //CONG NOI PC1 VA PC2
                            if (dbPC1 != 0 && dbHSL != Convert.ToDouble(reader["HSL"]))
                            {
                                newRow["LOAIPC"] = Environment.NewLine + "CV";
                                newRow["MUCPC"] = Environment.NewLine + String.Format("{0:0.##}", Math.Abs(dbPC1));
                                //dieu chinh chenh lech tang bhxh
                                if (dbPC1 > 0)
                                {
                                    newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch t¨ng. ";

                                }
                                //dieu chinh chenh lech giam bhxh
                                else if (dbPC1 < 0)
                                {
                                    newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch gi¶m. ";
                                }
                            }
                            //TRUONG HOP PC2
                            if (dbPC2 != 0 && dbHSL != Convert.ToDouble(reader["HSL"]))
                            {
                                newRow["LOAIPC"] = Environment.NewLine + "TV";
                                newRow["MUCPC"] = Environment.NewLine + Math.Abs(dbPC2).ToString() + "%";
                                //dieu chinh chenh lech tang bhxh
                                if (dbPC2 > 0)
                                {
                                    newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch t¨ng. ";
                                }
                                //dieu chinh chenh lech giam bhxh
                                else if (dbPC2 < 0)
                                {
                                    newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch gi¶m. ";
                                }
                            }
                            //TRUONG HOP PC3
                            if (dbPC3 != 0 && dbHSL != Convert.ToDouble(reader["HSL"]))
                            {
                                newRow["LOAIPC"] = Environment.NewLine + "TN";
                                newRow["MUCPC"] = Environment.NewLine + Math.Abs(dbPC3).ToString() + "%";
                                //dieu chinh chenh lech tang bhxh
                                if (dbPC3 > 0)
                                {
                                    newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch t¨ng. ";
                                }
                                //dieu chinh chenh lech giam bhxh
                                else if (dbPC3 < 0)
                                {
                                    newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch gi¶m. ";
                                }
                            }
                            newRow["NOIDUNG"] = newRow["NOIDUNG"] + ModuleBHXH.ChangeToCamel(FlxDetail.Rows[i]["Tendvi"].ToString());
                            newRow["TLBHXH"] = string.Format("{0:##}", reader["Tyle_BHXH"]) + "%";
                            dsIntoroi.Tables[0].Rows.Add(newRow);
                        }
                        else if (dbHSL == 0)
                        {
                            //truong hop PC1
                            if (dbPC1 != 0)
                            {
                                newRow["LOAIPC"] = "CV";
                                newRow["MUCPC"] = String.Format("{0:0.00}", Math.Abs(dbPC1));
                                //dieu chinh chenh lech tang bhxh
                                if (dbPC1 > 0)
                                {
                                    newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch t¨ng. ";
                                }
                                //dieu chinh chenh lech giam bhxh
                                else if (dbPC1 < 0)
                                {
                                    newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch gi¶m. ";
                                }
                                //PC2 <> 0
                                if (dbPC2 != 0)
                                {
                                    newRow["LOAIPC"] = Environment.NewLine + "TV";
                                    newRow["MUCPC"] = Environment.NewLine + Math.Abs(dbPC2).ToString() + "%";

                                    //dieu chinh chenh lech tang bhxh
                                    if (dbPC2 > 0)
                                    {
                                        newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch t¨ng. ";
                                    }
                                    //dieu chinh chenh lech giam bhxh
                                    else if (dbPC2 < 0)
                                    {
                                        newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch gi¶m. ";
                                    }
                                }
                                //PC3 <> 0
                                if (dbPC3 != 0)
                                {
                                    newRow["LOAIPC"] = Environment.NewLine + "TN";
                                    newRow["MUCPC"] = Environment.NewLine + Math.Abs(dbPC2).ToString() + "%";

                                    //dieu chinh chenh lech tang bhxh
                                    if (dbPC3 > 0)
                                    {
                                        newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch t¨ng. ";
                                    }
                                    //dieu chinh chenh lech giam bhxh
                                    else if (dbPC3 < 0)
                                    {
                                        newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch gi¶m. ";
                                    }
                                }
                                newRow["NOIDUNG"] = newRow["NOIDUNG"] + ModuleBHXH.ChangeToCamel(FlxDetail.Rows[i]["Tendvi"].ToString());
                                newRow["TLBHXH"] = string.Format("{0:##}", reader["Tyle_BHXH"]) + "%";
                                dsIntoroi.Tables[0].Rows.Add(newRow);
                            }
                            else if (dbPC2 != 0)
                            {
                                newRow["LOAIPC"] = "TV";
                                newRow["MUCPC"] = Math.Abs(dbPC2).ToString() + "%";
                                //dieu chinh chenh lech tang bhxh
                                if (dbPC2 > 0)
                                {
                                    newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch t¨ng. ";
                                }
                                //dieu chinh chenh lech giam bhxh
                                else if (dbPC2 < 0)
                                {
                                    newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch gi¶m. ";
                                }
                                newRow["NOIDUNG"] = newRow["NOIDUNG"] + ModuleBHXH.ChangeToCamel(FlxDetail.Rows[i]["Tendvi"].ToString());
                                newRow["TLBHXH"] = string.Format("{0:##}", reader["Tyle_BHXH"]) + "%";
                                dsIntoroi.Tables[0].Rows.Add(newRow);

                            }
                            else if (dbPC3 != 0)
                            {
                                newRow["LOAIPC"] = "TN";
                                newRow["MUCPC"] = Math.Abs(dbPC3).ToString() + "%";
                                //dieu chinh chenh lech tang bhxh
                                if (dbPC3 > 0)
                                {
                                    newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch t¨ng. ";
                                }
                                //dieu chinh chenh lech giam bhxh
                                else if (dbPC3 < 0)
                                {
                                    newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch gi¶m. ";
                                }
                                newRow["NOIDUNG"] = newRow["NOIDUNG"] + ModuleBHXH.ChangeToCamel(FlxDetail.Rows[i]["Tendvi"].ToString());
                                newRow["TLBHXH"] = string.Format("{0:##}", reader["Tyle_BHXH"]) + "%";
                                dsIntoroi.Tables[0].Rows.Add(newRow);

                            }
                        }
                    }
                }//end if
            }
        }
        /// <summary>
        /// them phan dieu chinh bhtn
        /// </summary>
        /// <param name="i"></param>
        /// <param name="dsIntoroi"></param>
        private void DieuChinhBHTN(int i, InToRoi dsIntoroi)
        {

            DataRow newRow = null;
            SqlDataReader reader;
            double dbML, dbHSL, dbPC1, dbPC2 = 0;
            String queryString;
            using (SqlConnection connection =
            new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                connection.Open();

                queryString = "exec sp_executesql N'SELECT Sobhxh, Madvi, Maqt, Loaidt, Ma_Nte, Pa, Tuthang, Denthang, Congviec, ML_DK, HSL_DK,"
                + " PC1_DK, PC2_DK, PC3_DK, ML, HSL, PC1, PC2, PC3,  Tyle_BHXH, Tyle_BHTN, SPACE(50) As Phucap, 100.000 * 0 As HSTN, "
                + " 100.000 * 0 As HSNG, SPACE(250) AS Noidung, ''DC'' AS SX FROM MISBHXH_NT.dbo.HSC47_DTL  WHERE Sobhxh=@P1  AND Madvi=@P2  "
                + " AND ((LEFT(Maqt,6) BETWEEN @P3  AND @P4  AND Tuthang < @P5 )  OR (LEFT(Maqt,6) = @P6  AND Tuthang < @P7  AND"
                + " (SELECT TOP 1 Hsl+Pc1+Pc2+Pc3+Pc4+Pc5+Ml+Mlyt As ML FROM MISBHXH_NT.dbo.HSC47_DTL  WHERE Sobhxh=@P8  "
                + " AND Madvi=@P9  AND LEFT(Maqt,6)=Denthang AND LEFT(Maqt,6)=@P10   AND CHARINDEX(Pa,''TT/TU/TN/GN/DN/CD'')=0 "
                + " ORDER BY Maqt DESC)=0))  AND ((LoaiDT=''HS'' AND ((HSL_DK+PC1_DK+PC2_DK+PC3_DK+HSL+PC1+PC2+PC3 <> 0 AND "
                + " (HSL_DK<>HSL OR PC1_DK<>PC1 OR PC2_DK<>PC2 OR PC3_DK<>PC3) ) OR (HSL_DK+PC1_DK+PC2_DK+PC3_DK+HSL+PC1+PC2+PC3 =0 "
                + " AND CHARINDEX(Pa,''GH/OF/TS'')<>0)))  OR (Loaidt=''ML'' AND ((ML_DK+ML <> 0 AND ML_DK <> ML) OR (ML_DK+ML =0 AND "
                + " CHARINDEX(Pa,''GH/OF/TS'')<>0))) OR Pa=''CD'') AND CHARINDEX(Pa,''TT/TU'')=0 AND Tyle_BHTN > 0  ORDER BY Maqt, Tuthang, Denthang ', "
                + " N'@P1 varchar(16),@P2 varchar(7),@P3 varchar(6),@P4 varchar(6),@P5 varchar(6),@P6 varchar(6),@P7 varchar(6),"
                + " @P8 varchar(16),@P9 varchar(7),@P10 varchar(6)', '" + FlxDetail.Rows[i]["Sobhxh"].ToString() + "', '" + FlxDetail.Rows[i]["Madvi"].ToString() + "', '" + FlxDetail.Rows[i]["tuthang"].ToString() + "',"
                + " '" + FlxDetail.Rows[i]["Denthang"].ToString() + "', '" + FlxDetail.Rows[i]["Tuthang"].ToString() + "',"
                + " '" + (Convert.ToInt16(FlxDetail.Rows[i]["Tuthang"].ToString().Substring(0, 4)) + 1).ToString() + "01" + "', '" + FlxDetail.Rows[i]["Tuthang"].ToString() + "', '" + FlxDetail.Rows[i]["Sobhxh"].ToString() + "',"
                + "'" + FlxDetail.Rows[i]["Madvi"].ToString() + "', '" + (Convert.ToInt16(FlxDetail.Rows[i]["Tuthang"].ToString().Substring(0, 4)) + 1).ToString() + "01" + "'";
                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    newRow = dsIntoroi.Tables[0].NewRow();
                    newRow["KEYSL"] = FlxDetail.Rows[i]["KEYSL"];
                    newRow["SOBHXH"] = FlxDetail.Rows[i]["SOBHXH"];
                    newRow["HOTEN"] = FlxDetail.Rows[i]["HO"].ToString().Trim() + " " + FlxDetail.Rows[i]["TEN"].ToString().Trim();
                    newRow["TUTHANG"] = ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["TUTHANG"].ToString());
                    newRow["DENTHANG"] = ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["DENTHANG"].ToString());
                    newRow["LOAIXN"] = FlxDetail.Rows[i]["XACNHAN"].ToString();
                    newRow["TTCHITIET"] = ModuleBHXH.FormatThangNam(reader["TUTHANG"].ToString());
                    //newRow["PA"] = reader["PA"].ToString();
                    if (Convert.ToInt32(reader["DENTHANG"]) >= Convert.ToInt32(FlxDetail.Rows[i]["Tuthang"]))
                    {
                        newRow["DTCHITIET"] = ModuleBHXH.FormatThangNam((Convert.ToInt16(FlxDetail.Rows[i]["Tuthang"].ToString().Substring(0, 4)) - 1).ToString() + "12");
                    }
                    else
                    {
                        newRow["DTCHITIET"] = ModuleBHXH.FormatThangNam(reader["DENTHANG"].ToString());
                    }
                    if (FlxDetail.Rows[i]["XACNHAN"].ToString() == "QT")
                    {
                        newRow["TTDT"] = "Tõ Th¸ng " + newRow["TUTHANG"].ToString() + " §Õn Th¸ng " + newRow["DENTHANG"];
                    }
                    else if (FlxDetail.Rows[i]["XACNHAN"].ToString().Trim() == "")
                    {
                        newRow["TTDT"] = "N¨m : " + FlxDetail.Rows[i]["denthang"].ToString().Substring(0, 4);
                    }
                    else
                    {
                        newRow["TTDT"] = "N¨m : " + FlxDetail.Rows[i]["denthangxn"].ToString().Substring(0, 4);
                    }
                    dbML = Convert.ToDouble(reader["ML"]) - Convert.ToDouble(reader["ML_DK"]);
                    dbHSL = Convert.ToDouble(reader["HSL"]) - Convert.ToDouble(reader["HSL_DK"]);
                    dbPC1 = Convert.ToDouble(reader["PC1"]) - Convert.ToDouble(reader["PC1_DK"]);
                    if (Convert.ToDouble(reader["HSL"]) > 0 && Convert.ToDouble(reader["HSL_DK"]) > 0)
                    {
                        dbPC2 = Convert.ToInt16(Convert.ToDouble(reader["PC2"]) * 100 / Convert.ToDouble(reader["HSL"])) -
                            Convert.ToInt16(Convert.ToDouble(reader["PC2_DK"]) * 100 / Convert.ToDouble(reader["HSL_DK"]));
                    }
                    else if (Convert.ToDouble(reader["HSL"]) > 0)
                    {
                        dbPC2 = Convert.ToInt16(Convert.ToDouble(reader["PC2"]) * 100 / Convert.ToDouble(reader["HSL"]));
                    }
                    else if (Convert.ToDouble(reader["HSL_DK"]) > 0)
                    {
                        dbPC2 = -Convert.ToInt16(Convert.ToDouble(reader["PC2_DK"]) * 100 / Convert.ToDouble(reader["HSL_DK"]));
                    }
                    //truong hop ML
                    if (dbML != 0)
                    {
                        newRow["ML"] = string.Format("{0:###,##.###}", Math.Abs(dbML));
                        //CONG NOI THOI GIAN BHXH
                        if (dbML == Convert.ToDouble(reader["ML"]))
                        {
                            newRow["NOIDUNG"] = "§iÒu chØnh céng nèi thêi gian tham gia thÊt nghiÖp. ";
                        }
                        //dieu chinh chenh lech tang bhxh
                        else if (dbML > 0)
                        {
                            newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch t¨ng thÊt nghiÖp. ";
                        }
                        //dieu chinh chenh lech giam bhxh
                        else if (dbML < 0)
                        {
                            if (reader["PA"].ToString() == "TS")
                            {
                                newRow["ML"] = "";
                                newRow["NOIDUNG"] = "§iÒu chØnh gi¶m thêi gian tham gia thÊt nghiÖp. ";
                            }
                            else
                            {
                                newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch gi¶m thÊt nghiÖp. ";
                            }
                        }
                        newRow["NOIDUNG"] = newRow["NOIDUNG"] + ModuleBHXH.ChangeToCamel(FlxDetail.Rows[i]["Tendvi"].ToString());
                        newRow["TLBHXH"] = string.Format("{0:##}", Convert.ToInt16(Convert.ToInt16(reader["Tyle_BHTN"]) + 1)) + "%";
                        dsIntoroi.Tables[0].Rows.Add(newRow);
                    }
                    // TRUONG HOP HSL
                    else if (dbHSL != 0)
                    {
                        newRow["ML"] = string.Format("{0:###,#0.000}", Math.Abs(dbHSL));
                        //CONG NOI THOI GIAN BHXH
                        if (dbHSL == Convert.ToDouble(reader["HSL"]))
                        {
                            newRow["NOIDUNG"] = "§iÒu chØnh céng nèi thêi gian tham gia thÊt nghiÖp. ";
                            // ghep thep pc1 và pc2
                            if (dbPC1 != 0)
                            {
                                newRow["LOAIPC"] = "CV";
                                newRow["MUCPC"] = String.Format("{0:0.00}", Math.Abs(dbPC1));
                                if (dbPC2 != 0)
                                {
                                    newRow["LOAIPC"] = newRow["LOAIPC"] + Environment.NewLine + "TV";
                                    newRow["MUCPC"] = newRow["MUCPC"] + Environment.NewLine + Math.Abs(dbPC2).ToString() + "%";
                                }
                            }
                            else
                            {
                                if (dbPC2 != 0)
                                {
                                    newRow["LOAIPC"] = "TV";
                                    newRow["MUCPC"] = Math.Abs(dbPC2).ToString() + "%";
                                }
                            }

                        }
                        //dieu chinh chenh lech tang bhxh
                        else if (dbHSL > 0)
                        {

                            newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch t¨ng thÊt nghiÖp. ";


                        }

                        //dieu chinh chenh lech giam bhxh
                        else if (dbHSL < 0)
                        {
                            newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch gi¶m thÊt nghiÖp. ";


                        }

                        //CONG NOI PC1 VA PC2
                        if (dbPC1 != 0 && dbHSL != Convert.ToDouble(reader["HSL"]))
                        {
                            newRow["LOAIPC"] = Environment.NewLine + "CV";
                            newRow["MUCPC"] = Environment.NewLine + String.Format("{0:0.00}", Math.Abs(dbPC1));
                            //dieu chinh chenh lech tang bhxh
                            if (dbPC1 > 0)
                            {
                                newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch t¨ng thÊt nghiÖp. ";

                            }
                            //dieu chinh chenh lech giam bhxh
                            else if (dbPC1 < 0)
                            {
                                newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch gi¶m thÊt nghiÖp. ";
                            }

                        }
                        //TRUONG HOP PC2
                        if (dbPC2 != 0 && dbHSL != Convert.ToDouble(reader["HSL"]))
                        {
                            newRow["LOAIPC"] = newRow["LOAIPC"] + Environment.NewLine + "TV";
                            newRow["MUCPC"] = newRow["MUCPC"] + Environment.NewLine + Math.Abs(dbPC2).ToString() + "%";


                            //dieu chinh chenh lech tang bhxh
                            if (dbPC2 > 0)
                            {
                                newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch t¨ng thÊt nghiÖp. ";
                            }
                            //dieu chinh chenh lech giam bhxh
                            else if (dbPC2 < 0)
                            {
                                newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch gi¶m thÊt nghiÖp. ";
                            }



                        }
                        newRow["NOIDUNG"] = newRow["NOIDUNG"] + ModuleBHXH.ChangeToCamel(FlxDetail.Rows[i]["Tendvi"].ToString());
                        newRow["TLBHXH"] = string.Format("{0:##}", Convert.ToInt16(Convert.ToInt16(reader["Tyle_BHTN"]) + 1)) + "%";
                        dsIntoroi.Tables[0].Rows.Add(newRow);
                    }
                    else if (dbHSL == 0)
                    {
                        //truong hop PC1
                        if (dbPC1 != 0)
                        {
                            newRow["LOAIPC"] = "CV";
                            newRow["MUCPC"] = String.Format("{0:0.00}", Math.Abs(dbPC1));
                            //dieu chinh chenh lech tang bhxh
                            if (dbPC1 > 0)
                            {
                                newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch t¨ng thÊt nghiÖp. ";


                            }
                            //dieu chinh chenh lech giam bhxh
                            else if (dbPC1 < 0)
                            {
                                newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch gi¶m thÊt nghiÖp. ";

                            }
                            //PC2 <> 0
                            if (dbPC2 != 0)
                            {
                                newRow["LOAIPC"] = Environment.NewLine + "TV";
                                newRow["MUCPC"] = Environment.NewLine + Math.Abs(dbPC2).ToString() + "%";

                                //dieu chinh chenh lech tang bhxh
                                if (dbPC2 > 0)
                                {
                                    newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch t¨ng thÊt nghiÖp. ";
                                }
                                //dieu chinh chenh lech giam bhxh
                                else if (dbPC2 < 0)
                                {
                                    newRow["NOIDUNG"] = newRow["NOIDUNG"] + Environment.NewLine + "§iÒu chØnh chªnh lÖch gi¶m thÊt nghiÖp. ";
                                }
                            }
                            newRow["NOIDUNG"] = newRow["NOIDUNG"] + ModuleBHXH.ChangeToCamel(FlxDetail.Rows[i]["Tendvi"].ToString());
                            newRow["TLBHXH"] = string.Format("{0:##}", Convert.ToInt16(Convert.ToInt16(reader["Tyle_BHTN"]) + 1)) + "%";
                            dsIntoroi.Tables[0].Rows.Add(newRow);
                        }
                        else if (dbPC2 != 0)
                        {
                            newRow["LOAIPC"] = "TV";
                            newRow["MUCPC"] = Math.Abs(dbPC2).ToString() + "%";
                            //dieu chinh chenh lech tang bhxh
                            if (dbPC2 > 0)
                            {

                                newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch t¨ng thÊt nghiÖp. ";


                            }
                            //dieu chinh chenh lech giam bhxh
                            else if (dbPC2 < 0)
                            {
                                newRow["NOIDUNG"] = "§iÒu chØnh chªnh lÖch gi¶m thÊt nghiÖp. ";

                            }
                            newRow["NOIDUNG"] = newRow["NOIDUNG"] + ModuleBHXH.ChangeToCamel(FlxDetail.Rows[i]["Tendvi"].ToString());
                            newRow["TLBHXH"] = string.Format("{0:##}", Convert.ToInt16(Convert.ToInt16(reader["Tyle_BHTN"]) + 1)) + "%";
                            dsIntoroi.Tables[0].Rows.Add(newRow);

                        }
                    }
                }
            }
        }
        /// <summary>
        /// tinh bhtn
        /// </summary>
        /// <param name="dsIntoroi"></param>
        /// <param name="k"></param>
        private void Bhtn(InToRoi dsIntoroi, int k)
        {
            QuatrinhBHXH dsQuatrinh = new QuatrinhBHXH();
            DataRow newRow = null;
            DataRow oldRow = null;
            SqlCommand command;
            SqlDataReader reader;
            int i;
            //int nam = 0, thang = 0;
            string sobhxh = "", Maxqt = "", queryString;
            sobhxh = FlxDetail.Rows[k]["SoBHXH"].ToString();
            Maxqt = FlxDetail.Rows[k]["DenThang"].ToString();
            queryString = "exec sp_executesql N'EXEC QUATRINHTNG @P1 , @P2 , @P3 ', "
                           + " N'@P1 varchar(16),@P2 varchar(6),@P3 varchar(6)', '" + sobhxh + "', '200901', '" + Maxqt + "'";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                command = connection.CreateCommand();
                command.CommandText = queryString;
                connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    newRow = dsQuatrinh.Tables[0].NewRow();
                    if (reader["loaips"].ToString() == "1")
                    {

                        newRow["Madvi"] = reader["Madvi"];
                        newRow["Tuthang"] = reader["Maqt"].ToString().Substring(0, 6);
                        newRow["Loaidt"] = reader["Loaidt"];
                        newRow["Ma_nte"] = reader["Ma_nte"];
                        newRow["Mucluong"] = reader["ML"];
                        newRow["Hsl"] = reader["Hsl"];
                        if (reader["pc1"] != null) { newRow["PCCV"] = reader["pc1"]; }
                        if (reader["pc2"] != null) { newRow["PCTN"] = reader["pc2"]; }
                        if (reader["pc3"] != null) { newRow["PCNG"] = reader["pc3"]; }

                        newRow["pa"] = reader["pa"];
                        newRow["loaips"] = reader["loaips"];

                        if (reader["Congviec"].ToString().Trim() == "")
                        {
                            newRow["Congviec"] = FlxDetail.Rows[k]["MACV"];
                        }
                        else
                        {
                            newRow["Congviec"] = reader["Congviec"];
                        }
                        //sap xep theo maqt
                        for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
                        {
                            if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Tuthang"].ToString()) > Convert.ToInt32(newRow["Tuthang"].ToString()))
                            {

                                dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                                break;
                            }
                            else if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Tuthang"].ToString()) == Convert.ToInt32(newRow["Tuthang"].ToString()))
                            {
                                dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                                dsQuatrinh.Tables[0].Rows.RemoveAt(i + 1);
                                break;
                            }
                        }
                        if (dsQuatrinh.Tables[0].Rows.Count == i) { dsQuatrinh.Tables[0].Rows.Add(newRow); }
                    }
                    else if (reader["loaips"].ToString() == "2")  //loai ps=2
                    {
                        newRow["Madvi"] = reader["Madvi"];
                        newRow["Tuthang"] = reader["Tuthang"];
                        newRow["Denthang"] = reader["Denthang"];
                        newRow["Loaidt"] = reader["Loaidt"];
                        newRow["Ma_nte"] = reader["Ma_nte"];
                        newRow["Mucluong"] = reader["ML"];
                        newRow["Hsl"] = reader["Hsl"];
                        if (reader["pc1"] != null) { newRow["PCCV"] = reader["pc1"]; }
                        if (reader["pc2"] != null) { newRow["PCTN"] = reader["pc2"]; }
                        if (reader["pc3"] != null) { newRow["PCNG"] = reader["pc3"]; }

                        newRow["loaips"] = reader["loaips"];

                        newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                        newRow["pa"] = reader["pa"];
                        if (reader["Congviec"].ToString().Trim() == "")
                        {
                            newRow["Congviec"] = FlxDetail.Rows[k]["MACV"];
                        }
                        else
                        {
                            newRow["Congviec"] = reader["Congviec"];
                        }

                        //sap xep theo maqt
                        for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
                        {
                            if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Tuthang"].ToString()) > Convert.ToInt32(newRow["Tuthang"].ToString()))
                            {
                                dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                                break;
                            }
                            if (dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString() != "")
                            {
                                if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString()) > Convert.ToInt32(newRow["Tuthang"].ToString()))
                                {
                                    dsQuatrinh.Tables[0].Rows[i]["Denthang"] = Convert.ToInt32(newRow["Tuthang"].ToString()) - 1;
                                    if (dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(4) == "00")
                                    {
                                        dsQuatrinh.Tables[0].Rows[i]["DenThang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DenThang"].ToString().Substring(0, 4)) - 1;
                                        dsQuatrinh.Tables[0].Rows[i]["DenThang"] = dsQuatrinh.Tables[0].Rows[i]["DenThang"].ToString() + "12";
                                    }
                                    if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DenThang"]) < Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Tuthang"]))
                                    {
                                        dsQuatrinh.Tables[0].Rows[i].Delete();
                                        i = i - 1;
                                    }

                                }
                            }
                        }
                        if (dsQuatrinh.Tables[0].Rows.Count == i) { dsQuatrinh.Tables[0].Rows.Add(newRow); }


                    }
                }
                reader.Close();

            }
            //hoan chinh sap xep
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {
                oldRow = dsQuatrinh.Tables[0].Rows[i];
                //them den thang cho nhung thang khong co den thang
                if (oldRow["DenThang"].ToString() == "")
                {
                    //dong cuoi cung
                    if (i == dsQuatrinh.Tables[0].Rows.Count - 1)
                    {
                        oldRow["DenThang"] = Maxqt;
                        oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                        break;
                    }


                    oldRow["DenThang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString()) - 1;

                    if (oldRow["DenThang"].ToString().Substring(4) == "00")
                    {
                        oldRow["DenThang"] = Convert.ToInt32(oldRow["DenThang"].ToString().Substring(0, 4)) - 1;
                        oldRow["DenThang"] = oldRow["DenThang"].ToString() + "12";
                    }

                    if (i > 0 && Convert.ToInt32(oldRow["tuthang"]) < Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i - 1]["denThang"]))
                    {
                        oldRow.Delete();
                        i = i - 1;
                    }
                    else
                    {
                        oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                            Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                        if (Convert.ToInt32(oldRow["Sothang"]) == 0 || oldRow["Sothang"].ToString() == "")
                        {
                            oldRow.Delete();
                            i = i - 1;
                        }
                    }


                }
            }
            //them dong de hoan thanh qua trinh
            oldRow = null;
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
            {

                if (dsQuatrinh.Tables[0].Rows[i]["loaips"].ToString() == "1")
                {
                    oldRow = dsQuatrinh.Tables[0].Rows[i];
                }

                if (oldRow != null && DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString().Substring(4, 2) + "/01")) > 1 && dsQuatrinh.Tables[0].Rows[i]["pa"].ToString().Trim() != "")
                {
                    newRow = dsQuatrinh.Tables[0].NewRow();
                    newRow["Madvi"] = oldRow["Madvi"];
                    newRow["Tuthang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["denThang"]) + 1;
                    if (newRow["Tuthang"].ToString().Substring(4) == "13")
                    {
                        newRow["Tuthang"] = Convert.ToInt32(newRow["Tuthang"].ToString().Substring(0, 4)) + 1;
                        newRow["Tuthang"] = newRow["Tuthang"].ToString() + "01";
                    }
                    newRow["DenThang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString()) - 1;
                    if (newRow["DenThang"].ToString().Substring(4) == "00")
                    {
                        newRow["DenThang"] = Convert.ToInt32(newRow["DenThang"].ToString().Substring(0, 4)) - 1;
                        newRow["DenThang"] = newRow["DenThang"].ToString() + "12";
                    }
                    newRow["Loaidt"] = oldRow["Loaidt"];
                    newRow["Ma_nte"] = oldRow["Ma_nte"];
                    newRow["Mucluong"] = oldRow["Mucluong"];
                    newRow["Hsl"] = oldRow["Hsl"];
                    newRow["PCCV"] = oldRow["PCCV"];
                    newRow["PCTN"] = oldRow["PCTN"];
                    newRow["PCNG"] = oldRow["PCNG"];
                    newRow["PCKV"] = oldRow["PCKV"];
                    newRow["pa"] = oldRow["pa"];
                    newRow["Congviec"] = oldRow["Congviec"];
                    newRow["Tendvi"] = oldRow["Tendvi"];
                    newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                      Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                    dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                    i++;


                }
            }
            //merge
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
            {
                oldRow = dsQuatrinh.Tables[0].Rows[i];
                newRow = dsQuatrinh.Tables[0].Rows[i + 1];
                if (oldRow["Denthang"] is System.DBNull) { break; }
                if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) == 1)
                {

                    if (oldRow["Mucluong"].ToString() == newRow["Mucluong"].ToString() &&
                        oldRow["HSL"].ToString() == newRow["HSL"].ToString() &&
                         oldRow["PCCV"].ToString() == newRow["PCCV"].ToString() &&
                         oldRow["PCTN"].ToString() == newRow["PCTN"].ToString() &&
                         oldRow["PCNG"].ToString() == newRow["PCNG"].ToString() &&
                         oldRow["PCKV"].ToString() == newRow["PCKV"].ToString() &&
                         oldRow["PCCV"].ToString() == newRow["PCCV"].ToString())
                    {
                        newRow["Tuthang"] = oldRow["Tuthang"];
                        newRow["Sothang"] = Convert.ToInt32(newRow["Sothang"]) + Convert.ToInt32(oldRow["Sothang"]);
                        oldRow.Delete();
                        i = i - 1;
                    }
                }
                //Xoa dong trung
                else if (Convert.ToInt32(oldRow["tuThang"]) >= Convert.ToInt32(newRow["tuThang"]) && Convert.ToInt32(oldRow["denThang"]) <= Convert.ToInt32(newRow["denThang"]))
                {
                    oldRow.Delete();
                    i = i - 1;
                }
            }

            //them dong khong tham gia và cắt các dòng có thời gian trung nhau
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
            {
                oldRow = dsQuatrinh.Tables[0].Rows[i];
                newRow = dsQuatrinh.Tables[0].Rows[i + 1];
                //cat cac dong co thoi gian trung
                if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) <= 0)
                {
                    oldRow["Denthang"] = Convert.ToInt32(newRow["Tuthang"]) - 1;
                    if (oldRow["DenThang"].ToString().Substring(4) == "00")
                    {
                        oldRow["DenThang"] = Convert.ToInt32(oldRow["DenThang"].ToString().Substring(0, 4)) - 1;
                        oldRow["DenThang"] = oldRow["DenThang"].ToString() + "12";
                    }
                    oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                         Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                }
                //them dong ko tham gia
                else if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) > 1)
                {
                    DataRow ktgRow = dsQuatrinh.Tables[0].NewRow();
                    //newRow["Madvi"] = oldRow["Madvi"];
                    ktgRow["Tuthang"] = Convert.ToInt32(oldRow["denThang"]) + 1;
                    if (ktgRow["Tuthang"].ToString().Substring(4) == "13")
                    {
                        ktgRow["Tuthang"] = Convert.ToInt32(ktgRow["Tuthang"].ToString().Substring(0, 4)) + 1;
                        ktgRow["Tuthang"] = ktgRow["Tuthang"].ToString() + "01";
                    }
                    ktgRow["DenThang"] = Convert.ToInt32(newRow["Tuthang"].ToString()) - 1;

                    if (ktgRow["DenThang"].ToString().Substring(4) == "00")
                    {
                        ktgRow["DenThang"] = Convert.ToInt32(ktgRow["DenThang"].ToString().Substring(0, 4)) - 1;
                        ktgRow["DenThang"] = ktgRow["DenThang"].ToString() + "12";
                    }
                    ktgRow["Mucluong"] = 0;
                    ktgRow["Hsl"] = 0;
                    ktgRow["PCCV"] = 0;
                    ktgRow["PCTN"] = 0;
                    ktgRow["PCNG"] = 0;
                    ktgRow["PCKV"] = 0;

                    ktgRow["pa"] = "OF";
                    ktgRow["Tendvi"] = "Kh«ng tham gia";
                    ktgRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(ktgRow["Tuthang"].ToString().Substring(0, 4) + "/" + ktgRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                      Convert.ToDateTime(ktgRow["Denthang"].ToString().Substring(0, 4) + "/" + ktgRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                    dsQuatrinh.Tables[0].Rows.InsertAt(ktgRow, i + 1);


                }
            }
            //dua va dataset Intoroi
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {
                if (dsQuatrinh.Tables[0].Rows[i]["MUCLUONG"].ToString() != "0" || dsQuatrinh.Tables[0].Rows[i]["HSL"].ToString() != "0")
                {

                    newRow = dsIntoroi.Tables[1].NewRow();
                    newRow["KEYSL"] = FlxDetail.Rows[k]["KEYSL"];
                    newRow["SOBHXH"] = FlxDetail.Rows[k]["SOBHXH"];
                    newRow["HOTEN"] = FlxDetail.Rows[k]["HO"].ToString().Trim() + " " + FlxDetail.Rows[k]["TEN"].ToString();
                    newRow["LOAIXN"] = FlxDetail.Rows[k]["XACNHAN"].ToString();
                    newRow["TTCHITIET"] = ModuleBHXH.FormatThangNam(dsQuatrinh.Tables[0].Rows[i]["TUTHANG"].ToString());
                    newRow["DTCHITIET"] = ModuleBHXH.FormatThangNam(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"].ToString());
                    newRow["NOIDUNG"] = "§ãng B¶o HiÓm ThÊt NghiÖp";
                    newRow["TLBHXH"] = "3%";
                    if (Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCCV"]) > 0)
                    {
                        newRow["MUCPC"] = String.Format("{0:###,#0.000}", dsQuatrinh.Tables[0].Rows[i]["PCCV"]);
                        
                    }
                    if (Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCTN"]) > 0)
                    {
                        newRow["MUCPC"] = Convert.ToInt16(Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCTN"]) * 100 / Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["HSL"])).ToString() + "%";
                    }
                    if (Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCNG"]) > 0)
                    {
                        newRow["TNNGHE"] = Convert.ToInt16(Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCNG"]) * 100 /
                            (Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["HSL"]) +
                            Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCTN"]) +
                            Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCCV"]))).ToString() + "%";
                    }
                    //if (Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["PCKV"]) > 0)
                    //{
                    //    newRow["KHAC"] = String.Format("{0:###,#0.000}", dsQuatrinh.Tables[0].Rows[i]["PCKV"]);
                    //}
                    newRow["GIOITINH"] = FlxDetail.Rows[k]["GIOITINH"];
                    newRow["NGAYSINH"] = FlxDetail.Rows[k]["NGAYSINH"];
                    newRow["SOCMND"] = FlxDetail.Rows[k]["SOCMND"];
                    newRow["NGAYCMND"] = FlxDetail.Rows[k]["NGAYCMND"];
                    newRow["NOICAP"] = FlxDetail.Rows[k]["NOICAP"];
                    newRow["DIACHI"] = FlxDetail.Rows[k]["DIACHI"];
                    // newRow["MACV"] = FlxDetail.Rows[k]["MACV"];
                    newRow["DANTOC"] = FlxDetail.Rows[k]["DANTOC"];
                    newRow["NOIKHAI"] = FlxDetail.Rows[k]["NOIKHAI"];
                    newRow["QUOCTICH"] = FlxDetail.Rows[k]["QUOCTICH"];

                    //dsIntoroi.Tables[1].Rows.Add(newRow);

                    if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["MUCLUONG"]) != 0)
                    {
                        newRow["ML"] = string.Format("{0:###,##.###}", Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["MUCLUONG"]));

                    }
                    else if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["HSL"]) != 0)
                    {
                        newRow["ML"] = string.Format("{0:###,##.000}", Convert.ToDouble(dsQuatrinh.Tables[0].Rows[i]["HSL"]));

                    }

                    dsIntoroi.Tables[1].Rows.Add(newRow);
                }
            }

            dsQuatrinh.Tables[0].Rows.Clear();

        }
        private void Bhtn_hangnam(int k, string xacnhan, string thangbd, string thangkt, string thanggh, string Maxqt)
        {
            QuatrinhBHXH dsQuatrinh = new QuatrinhBHXH();
            QuatrinhBHXH dsTQuatrinh = new QuatrinhBHXH();
            DataRow newRow = null;
            DataRow oldRow = null;
            DataRow currentRow = null;
            SqlCommand command;
            SqlDataReader reader;
            int i, namtn, thangtn;
            string sobhxh = "", queryString, tuthangxntn, denthangxntn;
            sobhxh = FlxSobhxh.Rows[k]["SoBHXH"].ToString();
            queryString = "exec sp_executesql N'EXEC QUATRINHTNG @P1 , @P2 , @P3 ', "
                           + " N'@P1 varchar(16),@P2 varchar(6),@P3 varchar(6)', '" + sobhxh + "', '200901', '" + Maxqt + "'";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                command = connection.CreateCommand();
                command.CommandText = queryString;
                connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    newRow = dsTQuatrinh.Tables[0].NewRow();
                    newRow["Madvi"] = reader["Madvi"];
                    newRow["Maqt"] = reader["Maqt"].ToString().Substring(0, 6);
                    newRow["Tuthang"] = reader["Tuthang"];
                    newRow["Denthang"] = reader["Denthang"];
                    newRow["Loaidt"] = reader["Loaidt"];
                    newRow["Ma_nte"] = reader["Ma_nte"];
                    newRow["Mucluong"] = reader["ML"];
                    newRow["Hsl"] = reader["Hsl"];
                    if (reader["pc1"] != null) { newRow["PCCV"] = reader["pc1"]; }
                    if (reader["pc2"] != null) { newRow["PCTN"] = reader["pc2"]; }
                    if (reader["pc3"] != null) { newRow["PCNG"] = reader["pc3"]; }
                    newRow["PCKV"] = 0;
                    newRow["pa"] = reader["pa"];
                    newRow["loaips"] = reader["loaips"];
                    if (reader["Congviec"].ToString().Trim() == "")
                    {
                        newRow["Congviec"] = FlxSobhxh.Rows[k]["MACV"];
                    }
                    else
                    {
                        newRow["Congviec"] = reader["Congviec"];
                    }
                    dsTQuatrinh.Tables[0].Rows.Add(newRow);

                }
                //ket thuc while
                reader.Close();
            }//ket thuc using
            for (int j = 0; j < dsTQuatrinh.Tables[0].Rows.Count; j++)
            {
                currentRow = dsTQuatrinh.Tables[0].Rows[j];
                if (Convert.ToInt32(currentRow["Maqt"]) <= Convert.ToInt32(thanggh))
                {
                    newRow = dsQuatrinh.Tables[0].NewRow();
                    if (currentRow["loaips"].ToString() == "1")
                    {

                        newRow["Madvi"] = currentRow["Madvi"];
                        newRow["Tuthang"] = currentRow["Maqt"];
                        newRow["Loaidt"] = currentRow["Loaidt"];
                        newRow["Ma_nte"] = currentRow["Ma_nte"];
                        newRow["Mucluong"] = currentRow["Mucluong"];
                        newRow["Hsl"] = currentRow["Hsl"];
                        newRow["PCCV"] = currentRow["PCCV"];
                        newRow["PCTN"] = currentRow["PCTN"];
                        newRow["PCNG"] = currentRow["PCNG"];
                        newRow["PCKV"] = 0;
                        newRow["pa"] = currentRow["pa"];
                        newRow["loaips"] = currentRow["loaips"];
                        newRow["Congviec"] = currentRow["Congviec"];

                        //sap xep theo maqt
                        for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
                        {
                            currentRow = dsQuatrinh.Tables[0].Rows[i];
                            if (Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["Tuthang"]))
                            {

                                insertNewRow(dsQuatrinh, newRow, Convert.ToInt32(currentRow["Tuthang"]), i);
                                break;
                            }
                            else if (Convert.ToInt32(newRow["Tuthang"]) == Convert.ToInt32(currentRow["Tuthang"]))
                            {
                                newRow["Denthang"] = currentRow["Denthang"];
                                newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                                dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                                dsQuatrinh.Tables[0].Rows.RemoveAt(i + 1);
                                break;
                            }
                            else if (Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["Tuthang"])
                                && Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["Denthang"]))
                            {
                                newRow["Denthang"] = currentRow["Denthang"];
                                UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                                newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                                dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                                break;
                            }
                            else if (Convert.ToInt32(newRow["Tuthang"]) == Convert.ToInt32(currentRow["Denthang"]))
                            {
                                UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                                newRow["Denthang"] = newRow["Tuthang"];
                                newRow["Sothang"] = 0;
                                dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                                break;
                            }
                        }
                        if (dsQuatrinh.Tables[0].Rows.Count == 0) // dong dau tien trong dataset
                        {
                            newRow["denthang"] = Maxqt;
                            newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                            dsQuatrinh.Tables[0].Rows.Add(newRow);
                        }
                        else if (dsQuatrinh.Tables[0].Rows.Count == i) //dong cuoi dung trong dataset
                        {
                            dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"] = Convert.ToInt32(newRow["Tuthang"]) - 1;
                            if (dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"].ToString().Substring(4) == "00")
                            {
                                dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"].ToString().Substring(0, 4)) - 1;
                                dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"] = dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"].ToString() + "12";
                            }
                            dsQuatrinh.Tables[0].Rows[i - 1]["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i - 1]["Tuthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i - 1]["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                            if (Convert.ToInt32(newRow["tuthang"]) <= Convert.ToInt32(Maxqt))
                            {
                                newRow["Denthang"] = Maxqt;
                                newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                                dsQuatrinh.Tables[0].Rows.Add(newRow);
                            }
                        }
                    }
                    else if (currentRow["loaips"].ToString() == "2")  //loai ps=2
                    {
                        newRow["Madvi"] = currentRow["Madvi"];
                        newRow["Tuthang"] = currentRow["Tuthang"];
                        newRow["Denthang"] = currentRow["Denthang"];
                        newRow["Loaidt"] = currentRow["Loaidt"];
                        newRow["Ma_nte"] = currentRow["Ma_nte"];
                        newRow["Mucluong"] = currentRow["Mucluong"];
                        newRow["Hsl"] = currentRow["Hsl"];
                        newRow["PCCV"] = currentRow["PCCV"];
                        newRow["PCTN"] = currentRow["PCTN"];
                        newRow["PCNG"] = currentRow["PCNG"];
                        newRow["PCKV"] = currentRow["PCKV"];
                        newRow["loaips"] = currentRow["loaips"];
                        newRow["Congviec"] = currentRow["Congviec"];
                        newRow["pa"] = currentRow["pa"];
                        newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;


                        //sap xep theo ma qua trinh
                        switch (newRow["pa"].ToString().Trim())
                        {

                            case "":
                            case "DC":
                            case "DN":
                            case "TM":
                            case "TC":
                            case "TD":
                            case "ON":
                            case "GC":
                            case "GD":
                            case "GH":
                            case "OF":
                                PA_DC(dsQuatrinh, newRow);
                                break;
                            case "TS":
                                PA_DC(dsQuatrinh, newRow);
                                break;

                        }
                    }
                }//ket thuc if loc giu lieu
            }//ket thuc dong for
            //them dong de hoan thanh qua trinh
            oldRow = null;
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {

                if (dsQuatrinh.Tables[0].Rows[i]["loaips"].ToString() == "1")
                {
                    oldRow = dsQuatrinh.Tables[0].Rows[i];
                }
                //truong hop ngay phat sinh khong phai lai thang cuoi cua qua trinh
                if (i == dsQuatrinh.Tables[0].Rows.Count - 1)
                {
                    //chi xet truong hop ps = 2
                    if (dsQuatrinh.Tables[0].Rows[i]["loaips"].ToString() == "2" && oldRow != null)
                    {
                        //them dong de lien tuc qua trinh
                        if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["denthang"]) < Convert.ToInt32(thangkt))
                        {
                            newRow = dsQuatrinh.Tables[0].NewRow();
                            newRow["Madvi"] = oldRow["Madvi"];
                            newRow["Tuthang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["denThang"]) + 1;
                            if (newRow["Tuthang"].ToString().Substring(4) == "13")
                            {
                                newRow["Tuthang"] = Convert.ToInt32(newRow["Tuthang"].ToString().Substring(0, 4)) + 1;
                                newRow["Tuthang"] = newRow["Tuthang"].ToString() + "01";
                            }
                            newRow["DenThang"] = thangkt;
                            newRow["Loaidt"] = oldRow["Loaidt"];
                            newRow["Ma_nte"] = oldRow["Ma_nte"];
                            newRow["Mucluong"] = oldRow["Mucluong"];
                            newRow["Hsl"] = oldRow["Hsl"];
                            newRow["PCCV"] = oldRow["PCCV"];
                            newRow["PCTN"] = oldRow["PCTN"];
                            newRow["PCNG"] = oldRow["PCNG"];
                            newRow["PCKV"] = oldRow["PCKV"];
                            newRow["pa"] = oldRow["pa"];
                            newRow["Congviec"] = oldRow["Congviec"];
                            newRow["Tendvi"] = oldRow["Tendvi"];
                            newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                              Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        }
                    }
                }
                else
                {
                    if (oldRow != null && DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(4, 2) + "/01"),
                            Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString().Substring(4, 2) + "/01")) > 1 && dsQuatrinh.Tables[0].Rows[i]["pa"].ToString().Trim() != "")
                    {
                        newRow = dsQuatrinh.Tables[0].NewRow();
                        newRow["Madvi"] = oldRow["Madvi"];
                        newRow["Tuthang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["denThang"]) + 1;
                        if (newRow["Tuthang"].ToString().Substring(4) == "13")
                        {
                            newRow["Tuthang"] = Convert.ToInt32(newRow["Tuthang"].ToString().Substring(0, 4)) + 1;
                            newRow["Tuthang"] = newRow["Tuthang"].ToString() + "01";
                        }
                        newRow["DenThang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString()) - 1;
                        if (newRow["DenThang"].ToString().Substring(4) == "00")
                        {
                            newRow["DenThang"] = Convert.ToInt32(newRow["DenThang"].ToString().Substring(0, 4)) - 1;
                            newRow["DenThang"] = newRow["DenThang"].ToString() + "12";
                        }
                        newRow["Loaidt"] = oldRow["Loaidt"];
                        newRow["Ma_nte"] = oldRow["Ma_nte"];
                        newRow["Mucluong"] = oldRow["Mucluong"];
                        newRow["Hsl"] = oldRow["Hsl"];
                        newRow["PCCV"] = oldRow["PCCV"];
                        newRow["PCTN"] = oldRow["PCTN"];
                        newRow["PCNG"] = oldRow["PCNG"];
                        newRow["PCKV"] = oldRow["PCKV"];
                        newRow["pa"] = oldRow["pa"];
                        newRow["Congviec"] = oldRow["Congviec"];
                        newRow["Tendvi"] = oldRow["Tendvi"];
                        newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                          Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        i++;

                    }
                }//ket thu else
            }//ket thu them dong de hoan thanh qua trinh
            //merge
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
            {
                oldRow = dsQuatrinh.Tables[0].Rows[i];
                newRow = dsQuatrinh.Tables[0].Rows[i + 1];
                if (oldRow["Denthang"] is System.DBNull) { break; }
                if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) == 1)
                {

                    if (oldRow["Mucluong"].ToString() == newRow["Mucluong"].ToString() &&
                        oldRow["HSL"].ToString() == newRow["HSL"].ToString() &&
                         oldRow["PCCV"].ToString() == newRow["PCCV"].ToString() &&
                         oldRow["PCTN"].ToString() == newRow["PCTN"].ToString() &&
                         oldRow["PCNG"].ToString() == newRow["PCNG"].ToString() &&
                         oldRow["PCKV"].ToString() == newRow["PCKV"].ToString() &&
                         oldRow["PCCV"].ToString() == newRow["PCCV"].ToString())
                    {
                        newRow["Tuthang"] = oldRow["Tuthang"];
                        newRow["Sothang"] = Convert.ToInt32(newRow["Sothang"]) + Convert.ToInt32(oldRow["Sothang"]);
                        oldRow.Delete();
                        i = i - 1;
                    }
                }
                //Xoa dong trung
                else if (Convert.ToInt32(oldRow["tuThang"]) >= Convert.ToInt32(newRow["tuThang"]) && Convert.ToInt32(oldRow["denThang"]) <= Convert.ToInt32(newRow["denThang"]))
                {
                    oldRow.Delete();
                    i = i - 1;
                }
            }

            //them dong khong tham gia và cắt các dòng có thời gian trung nhau
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
            {
                oldRow = dsQuatrinh.Tables[0].Rows[i];
                newRow = dsQuatrinh.Tables[0].Rows[i + 1];
                //cat cac dong co thoi gian trung
                if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) <= 0)
                {
                    oldRow["Denthang"] = Convert.ToInt32(newRow["Tuthang"]) - 1;
                    if (oldRow["DenThang"].ToString().Substring(4) == "00")
                    {
                        oldRow["DenThang"] = Convert.ToInt32(oldRow["DenThang"].ToString().Substring(0, 4)) - 1;
                        oldRow["DenThang"] = oldRow["DenThang"].ToString() + "12";
                    }
                    oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                         Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                }
                //them dong ko tham gia
                else if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) > 1)
                {
                    DataRow ktgRow = dsQuatrinh.Tables[0].NewRow();
                    //newRow["Madvi"] = oldRow["Madvi"];
                    ktgRow["Tuthang"] = Convert.ToInt32(oldRow["denThang"]) + 1;
                    if (ktgRow["Tuthang"].ToString().Substring(4) == "13")
                    {
                        ktgRow["Tuthang"] = Convert.ToInt32(ktgRow["Tuthang"].ToString().Substring(0, 4)) + 1;
                        ktgRow["Tuthang"] = ktgRow["Tuthang"].ToString() + "01";
                    }
                    ktgRow["DenThang"] = Convert.ToInt32(newRow["Tuthang"].ToString()) - 1;

                    if (ktgRow["DenThang"].ToString().Substring(4) == "00")
                    {
                        ktgRow["DenThang"] = Convert.ToInt32(ktgRow["DenThang"].ToString().Substring(0, 4)) - 1;
                        ktgRow["DenThang"] = ktgRow["DenThang"].ToString() + "12";
                    }
                    ktgRow["Mucluong"] = 0;
                    ktgRow["Hsl"] = 0;
                    ktgRow["PCCV"] = 0;
                    ktgRow["PCTN"] = 0;
                    ktgRow["PCNG"] = 0;
                    ktgRow["PCKV"] = 0;

                    ktgRow["pa"] = "OF";
                    ktgRow["Tendvi"] = "Kh«ng tham gia";
                    ktgRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(ktgRow["Tuthang"].ToString().Substring(0, 4) + "/" + ktgRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                      Convert.ToDateTime(ktgRow["Denthang"].ToString().Substring(0, 4) + "/" + ktgRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                    dsQuatrinh.Tables[0].Rows.InsertAt(ktgRow, i + 1);


                }
            }
            namtn = 0;
            thangtn = 0;
            tuthangxntn = "";
            denthangxntn = "";
            //dua va dataset dsKQuaTrinh
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {
                if (dsQuatrinh.Tables[0].Rows[i]["MUCLUONG"].ToString() != "0" || dsQuatrinh.Tables[0].Rows[i]["HSL"].ToString() != "0")
                {
                    if (xacnhan == FlxSobhxh.Rows[k]["xacnhan"].ToString() && xacnhan != "")
                    {
                        if (i == 0)
                        {
                            tuthangxntn = dsQuatrinh.Tables[0].Rows[i]["TUTHANG"].ToString();
                        }
                        denthangxntn = dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString();
                        //chi tinh thoi gian tham gia bhxh
                        if (dsQuatrinh.Tables[0].Rows[i]["Tendvi"].ToString() != "Kh«ng tham gia")
                        {
                            ModuleBHXH.KhoangThoiGian(ModuleBHXH.FormatThangNam(dsQuatrinh.Tables[0].Rows[i]["TUTHANG"].ToString()),
                                 ModuleBHXH.FormatThangNam(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"].ToString()), ref namtn, ref thangtn);
                        }
                    }
                    if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"]) >= Convert.ToInt32(thangbd)
                               && Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["TUTHANG"]) <= Convert.ToInt32(thangkt))
                    {
                        if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["TUTHANG"]) < Convert.ToInt32(thangbd))
                        {
                            dsQuatrinh.Tables[0].Rows[i]["TUTHANG"] = thangbd;
                        }
                        if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"]) > Convert.ToInt32(thangkt))
                        {
                            dsQuatrinh.Tables[0].Rows[i]["DENTHANG"] = thangkt;
                        }
                        newRow = dsKQuatrinh.Tables[0].NewRow();
                        newRow["Maqt"] = thangbd;
                        newRow["Madvi"] = dsQuatrinh.Tables[0].Rows[i]["Madvi"];
                        newRow["SOBHXH"] = FlxSobhxh.Rows[k]["SOBHXH"];
                        newRow["TUTHANG"] = dsQuatrinh.Tables[0].Rows[i]["TUTHANG"].ToString();
                        newRow["DENTHANG"] = dsQuatrinh.Tables[0].Rows[i]["DENTHANG"].ToString();
                        newRow["Loaidt"] = dsQuatrinh.Tables[0].Rows[i]["Loaidt"];
                        newRow["Ma_nte"] = dsQuatrinh.Tables[0].Rows[i]["Ma_nte"];
                        newRow["CONGVIEC"] = "§ãng b¶o hiÓm thÊt nghiÖp";
                        newRow["TLBHXH"] = "3";
                        newRow["mucluong"] = dsQuatrinh.Tables[0].Rows[i]["mucluong"];
                        newRow["hsl"] = dsQuatrinh.Tables[0].Rows[i]["hsl"];
                        newRow["PCCV"] = dsQuatrinh.Tables[0].Rows[i]["PCCV"];
                        newRow["PCTN"] = dsQuatrinh.Tables[0].Rows[i]["PCTN"];
                        newRow["PCNG"] = dsQuatrinh.Tables[0].Rows[i]["PCNG"];
                        newRow["PCKV"] = dsQuatrinh.Tables[0].Rows[i]["PCKV"];
                        newRow["sothang"] = dsQuatrinh.Tables[0].Rows[i]["sothang"];
                        newRow["pa"] = dsQuatrinh.Tables[0].Rows[i]["pa"];
                        dsKQuatrinh.Tables[0].Rows.Add(newRow);
                    }
                }
            }
            dsQuatrinh.Tables[0].Rows.Clear();
            if (xacnhan == FlxSobhxh.Rows[k]["xacnhan"].ToString() && xacnhan != "")//truong co chi tiet trong khoang thoi gian 
            {
                GetDataBHTNOnFlex(xacnhan, namtn, thangtn, tuthangxntn, denthangxntn);
            }
            thangbd = (Convert.ToInt32(thangkt.Substring(0, 4)) + 1).ToString();
            thangbd = thangbd + "01";
        }
        //private void Bhtn_hangnam(int k, string xacnhan, string thangbd, string thangkt, string thanggh, string Maxqt)
        //{
        //    QuatrinhBHXH dsQuatrinh = new QuatrinhBHXH();
        //    QuatrinhBHXH dsTQuatrinh = new QuatrinhBHXH();
        //    DataRow newRow = null;
        //    DataRow oldRow = null;
        //    DataRow currentRow = null;
        //    SqlCommand command;
        //    SqlDataReader reader;
        //    int i,namtn,thangtn;
        //    string sobhxh = "", queryString,tuthangxntn,denthangxntn;
        //    sobhxh = FlxSobhxh.Rows[k]["SoBHXH"].ToString();
        //    queryString = "exec sp_executesql N'EXEC QUATRINHTNG @P1 , @P2 , @P3 ', "
        //                   + " N'@P1 varchar(16),@P2 varchar(6),@P3 varchar(6)', '" + sobhxh + "', '200901', '" + Maxqt + "'";
        //    using (SqlConnection connection = new SqlConnection(connectionString))
        //    {
        //        command = connection.CreateCommand();
        //        command.CommandText = queryString;
        //        connection.Open();
        //        reader = command.ExecuteReader();
        //        while (reader.Read())
        //        {
        //            newRow = dsTQuatrinh.Tables[0].NewRow();
        //            newRow["Madvi"] = reader["Madvi"];
        //            newRow["Maqt"] = reader["Maqt"].ToString().Substring(0, 6);
        //            newRow["Tuthang"] = reader["Tuthang"];
        //            newRow["Denthang"] = reader["Denthang"];
        //            newRow["Loaidt"] = reader["Loaidt"];
        //            newRow["Ma_nte"] = reader["Ma_nte"];
        //            newRow["Mucluong"] = reader["ML"];
        //            newRow["Hsl"] = reader["Hsl"];
        //            if (reader["pc1"] != null) { newRow["PCCV"] = reader["pc1"]; }
        //            if (reader["pc2"] != null) { newRow["PCTN"] = reader["pc2"]; }
        //            if (reader["pc3"] != null) { newRow["PCNG"] = reader["pc3"]; }
        //            newRow["PCKV"] = 0;
        //            newRow["pa"] = reader["pa"];
        //            newRow["loaips"] = reader["loaips"];
        //            if (reader["Congviec"].ToString().Trim() == "")
        //            {
        //                newRow["Congviec"] = FlxSobhxh.Rows[k]["MACV"];
        //            }
        //            else
        //            {
        //                newRow["Congviec"] = reader["Congviec"];
        //            }
        //            dsTQuatrinh.Tables[0].Rows.Add(newRow);

        //        }
        //        //ket thuc while
        //        reader.Close();
        //    }//ket thuc using
        //    for (int j = 0; j < dsTQuatrinh.Tables[0].Rows.Count; j++)
        //    {
        //        currentRow = dsTQuatrinh.Tables[0].Rows[j];
        //        if (Convert.ToInt32(currentRow["Maqt"]) <= Convert.ToInt32(thanggh))
        //        {
        //            newRow = dsQuatrinh.Tables[0].NewRow();
        //            if (currentRow["loaips"].ToString() == "1")
        //            {

        //                newRow["Madvi"] = currentRow["Madvi"];
        //                newRow["Tuthang"] = currentRow["Maqt"];
        //                newRow["Loaidt"] = currentRow["Loaidt"];
        //                newRow["Ma_nte"] = currentRow["Ma_nte"];
        //                newRow["Mucluong"] = currentRow["Mucluong"];
        //                newRow["Hsl"] = currentRow["Hsl"];
        //                newRow["PCCV"] = currentRow["PCCV"];
        //                newRow["PCTN"] = currentRow["PCTN"];
        //                newRow["PCNG"] = currentRow["PCNG"];
        //                newRow["PCKV"] = 0;
        //                newRow["pa"] = currentRow["pa"];
        //                newRow["loaips"] = currentRow["loaips"];
        //                newRow["Congviec"] = currentRow["Congviec"];
                        
        //                //sap xep theo maqt
        //                for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
        //                {
        //                    if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Tuthang"].ToString()) > Convert.ToInt32(newRow["Tuthang"].ToString()))
        //                    {

        //                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
        //                        break;
        //                    }
        //                    else if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Tuthang"].ToString()) == Convert.ToInt32(newRow["Tuthang"].ToString()))
        //                    {
        //                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
        //                        dsQuatrinh.Tables[0].Rows.RemoveAt(i + 1);
        //                        break;
        //                    }
        //                }
        //                if (dsQuatrinh.Tables[0].Rows.Count == i) { dsQuatrinh.Tables[0].Rows.Add(newRow); }
        //            }
        //            else if (currentRow["loaips"].ToString() == "2" )  //loai ps=2
        //            {
        //                newRow["Madvi"] = currentRow["Madvi"];
        //                newRow["Tuthang"] = currentRow["Tuthang"];
        //                newRow["Denthang"] = currentRow["Denthang"];
        //                newRow["Loaidt"] = currentRow["Loaidt"];
        //                newRow["Ma_nte"] = currentRow["Ma_nte"];
        //                newRow["Mucluong"] = currentRow["Mucluong"];
        //                newRow["Hsl"] = currentRow["Hsl"];
        //                newRow["PCCV"] = currentRow["PCCV"];
        //                newRow["PCTN"] = currentRow["PCTN"];
        //                newRow["PCNG"] = currentRow["PCNG"];
        //                newRow["PCKV"] = currentRow["PCKV"];
        //                newRow["loaips"] = currentRow["loaips"];
        //                newRow["Congviec"] = currentRow["Congviec"];
        //                newRow["pa"] = currentRow["pa"];
        //                newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
        //                        Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                       

        //                //sap xep theo maqt
        //                for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
        //                {
        //                    if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Tuthang"].ToString()) > Convert.ToInt32(newRow["Tuthang"].ToString()))
        //                    {
        //                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
        //                        break;
        //                    }
        //                    if (dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString() != "")
        //                    {
        //                        if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString()) > Convert.ToInt32(newRow["Tuthang"].ToString()))
        //                        {
        //                            dsQuatrinh.Tables[0].Rows[i]["Denthang"] = Convert.ToInt32(newRow["Tuthang"].ToString()) - 1;
        //                            if (dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(4) == "00")
        //                            {
        //                                dsQuatrinh.Tables[0].Rows[i]["DenThang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DenThang"].ToString().Substring(0, 4)) - 1;
        //                                dsQuatrinh.Tables[0].Rows[i]["DenThang"] = dsQuatrinh.Tables[0].Rows[i]["DenThang"].ToString() + "12";
        //                            }
        //                            if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DenThang"]) < Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Tuthang"]))
        //                            {
        //                                dsQuatrinh.Tables[0].Rows[i].Delete();
        //                                i = i - 1;
        //                            }

        //                        }
        //                    }
        //                }
        //                if (dsQuatrinh.Tables[0].Rows.Count == i) { dsQuatrinh.Tables[0].Rows.Add(newRow); }
        //            }
        //        }//ket thuc if loc giu lieu
        //    }//ket thuc dong for
        //    //hoan chinh sap xep
        //    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
        //    {
        //        oldRow = dsQuatrinh.Tables[0].Rows[i];
        //        //them den thang cho nhung thang khong co den thang
        //        if (oldRow["DenThang"].ToString() == "")
        //        {
        //            //dong cuoi cung
        //            if (i == dsQuatrinh.Tables[0].Rows.Count - 1)
        //            {
        //                oldRow["DenThang"] = Maxqt;
        //                oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
        //                Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
        //                break;
        //            }
        //            oldRow["DenThang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString()) - 1;

        //            if (oldRow["DenThang"].ToString().Substring(4) == "00")
        //            {
        //                oldRow["DenThang"] = Convert.ToInt32(oldRow["DenThang"].ToString().Substring(0, 4)) - 1;
        //                oldRow["DenThang"] = oldRow["DenThang"].ToString() + "12";
        //            }

        //            if (i > 0 && Convert.ToInt32(oldRow["tuthang"]) < Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i - 1]["denThang"]))
        //            {
        //                oldRow.Delete();
        //                i = i - 1;
        //            }
        //            else
        //            {
        //                oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
        //                    Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
        //                if (Convert.ToInt32(oldRow["Sothang"]) == 0 || oldRow["Sothang"].ToString() == "")
        //                {
        //                    oldRow.Delete();
        //                    i = i - 1;
        //                }
        //            }


        //        }
        //    }
        //    //them dong de hoan thanh qua trinh
        //    oldRow = null;
        //    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
        //    {

        //        if (dsQuatrinh.Tables[0].Rows[i]["loaips"].ToString() == "1")
        //        {
        //            oldRow = dsQuatrinh.Tables[0].Rows[i];
        //        }
        //        //truong hop ngay phat sinh khong phai lai thang cuoi cua qua trinh
        //        if (i == dsQuatrinh.Tables[0].Rows.Count - 1)
        //        {
        //            //chi xet truong hop ps = 2
        //            if (dsQuatrinh.Tables[0].Rows[i]["loaips"].ToString() == "2" && oldRow != null )
        //            {
        //                //them dong de lien tuc qua trinh
        //                if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["denthang"]) < Convert.ToInt32(thangkt))
        //                {
        //                    newRow = dsQuatrinh.Tables[0].NewRow();
        //                    newRow["Madvi"] = oldRow["Madvi"];
        //                    newRow["Tuthang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["denThang"]) + 1;
        //                    if (newRow["Tuthang"].ToString().Substring(4) == "13")
        //                    {
        //                        newRow["Tuthang"] = Convert.ToInt32(newRow["Tuthang"].ToString().Substring(0, 4)) + 1;
        //                        newRow["Tuthang"] = newRow["Tuthang"].ToString() + "01";
        //                    }
        //                    newRow["DenThang"] = thangkt;
        //                    newRow["Loaidt"] = oldRow["Loaidt"];
        //                    newRow["Ma_nte"] = oldRow["Ma_nte"];
        //                    newRow["Mucluong"] = oldRow["Mucluong"];
        //                    newRow["Hsl"] = oldRow["Hsl"];
        //                    newRow["PCCV"] = oldRow["PCCV"];
        //                    newRow["PCTN"] = oldRow["PCTN"];
        //                    newRow["PCNG"] = oldRow["PCNG"];
        //                    newRow["PCKV"] = oldRow["PCKV"];
        //                    newRow["pa"] = oldRow["pa"];
        //                    newRow["Congviec"] = oldRow["Congviec"];
        //                    newRow["Tendvi"] = oldRow["Tendvi"];
        //                    newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
        //                      Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
        //                    dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
        //                }
        //            }
        //        }
        //        else
        //        {
        //            if (oldRow != null && DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString().Substring(4, 2) + "/01"),
        //                    Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString().Substring(4, 2) + "/01")) > 1 && dsQuatrinh.Tables[0].Rows[i]["pa"].ToString().Trim() != "")
        //            {
        //                newRow = dsQuatrinh.Tables[0].NewRow();
        //                newRow["Madvi"] = oldRow["Madvi"];
        //                newRow["Tuthang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["denThang"]) + 1;
        //                if (newRow["Tuthang"].ToString().Substring(4) == "13")
        //                {
        //                    newRow["Tuthang"] = Convert.ToInt32(newRow["Tuthang"].ToString().Substring(0, 4)) + 1;
        //                    newRow["Tuthang"] = newRow["Tuthang"].ToString() + "01";
        //                }
        //                newRow["DenThang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i + 1]["Tuthang"].ToString()) - 1;
        //                if (newRow["DenThang"].ToString().Substring(4) == "00")
        //                {
        //                    newRow["DenThang"] = Convert.ToInt32(newRow["DenThang"].ToString().Substring(0, 4)) - 1;
        //                    newRow["DenThang"] = newRow["DenThang"].ToString() + "12";
        //                }
        //                newRow["Loaidt"] = oldRow["Loaidt"];
        //                newRow["Ma_nte"] = oldRow["Ma_nte"];
        //                newRow["Mucluong"] = oldRow["Mucluong"];
        //                newRow["Hsl"] = oldRow["Hsl"];
        //                newRow["PCCV"] = oldRow["PCCV"];
        //                newRow["PCTN"] = oldRow["PCTN"];
        //                newRow["PCNG"] = oldRow["PCNG"];
        //                newRow["PCKV"] = oldRow["PCKV"];
        //                newRow["pa"] = oldRow["pa"];
        //                newRow["Congviec"] = oldRow["Congviec"];
        //                newRow["Tendvi"] = oldRow["Tendvi"];
        //                newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
        //                  Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
        //                dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
        //                i++;

        //            }
        //        }//ket thu else
        //    }//ket thu them dong de hoan thanh qua trinh
        //    //merge
        //    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
        //    {
        //        oldRow = dsQuatrinh.Tables[0].Rows[i];
        //        newRow = dsQuatrinh.Tables[0].Rows[i + 1];
        //        if (oldRow["Denthang"] is System.DBNull) { break; }
        //        if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
        //                Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) == 1)
        //        {

        //            if (oldRow["Mucluong"].ToString() == newRow["Mucluong"].ToString() &&
        //                oldRow["HSL"].ToString() == newRow["HSL"].ToString() &&
        //                 oldRow["PCCV"].ToString() == newRow["PCCV"].ToString() &&
        //                 oldRow["PCTN"].ToString() == newRow["PCTN"].ToString() &&
        //                 oldRow["PCNG"].ToString() == newRow["PCNG"].ToString() &&
        //                 oldRow["PCKV"].ToString() == newRow["PCKV"].ToString() &&
        //                 oldRow["PCCV"].ToString() == newRow["PCCV"].ToString())
        //            {
        //                newRow["Tuthang"] = oldRow["Tuthang"];
        //                newRow["Sothang"] = Convert.ToInt32(newRow["Sothang"]) + Convert.ToInt32(oldRow["Sothang"]);
        //                oldRow.Delete();
        //                i = i - 1;
        //            }
        //        }
        //        //Xoa dong trung
        //        else if (Convert.ToInt32(oldRow["tuThang"]) >= Convert.ToInt32(newRow["tuThang"]) && Convert.ToInt32(oldRow["denThang"]) <= Convert.ToInt32(newRow["denThang"]))
        //        {
        //            oldRow.Delete();
        //            i = i - 1;
        //        }
        //    }

        //    //them dong khong tham gia và cắt các dòng có thời gian trung nhau
        //    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count - 1; i++)
        //    {
        //        oldRow = dsQuatrinh.Tables[0].Rows[i];
        //        newRow = dsQuatrinh.Tables[0].Rows[i + 1];
        //        //cat cac dong co thoi gian trung
        //        if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
        //                Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) <= 0)
        //        {
        //            oldRow["Denthang"] = Convert.ToInt32(newRow["Tuthang"]) - 1;
        //            if (oldRow["DenThang"].ToString().Substring(4) == "00")
        //            {
        //                oldRow["DenThang"] = Convert.ToInt32(oldRow["DenThang"].ToString().Substring(0, 4)) - 1;
        //                oldRow["DenThang"] = oldRow["DenThang"].ToString() + "12";
        //            }
        //            oldRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Tuthang"].ToString().Substring(0, 4) + "/" + oldRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
        //                 Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

        //        }
        //        //them dong ko tham gia
        //        else if (DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(oldRow["Denthang"].ToString().Substring(0, 4) + "/" + oldRow["Denthang"].ToString().Substring(4, 2) + "/01"),
        //                Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01")) > 1)
        //        {
        //            DataRow ktgRow = dsQuatrinh.Tables[0].NewRow();
        //            //newRow["Madvi"] = oldRow["Madvi"];
        //            ktgRow["Tuthang"] = Convert.ToInt32(oldRow["denThang"]) + 1;
        //            if (ktgRow["Tuthang"].ToString().Substring(4) == "13")
        //            {
        //                ktgRow["Tuthang"] = Convert.ToInt32(ktgRow["Tuthang"].ToString().Substring(0, 4)) + 1;
        //                ktgRow["Tuthang"] = ktgRow["Tuthang"].ToString() + "01";
        //            }
        //            ktgRow["DenThang"] = Convert.ToInt32(newRow["Tuthang"].ToString()) - 1;

        //            if (ktgRow["DenThang"].ToString().Substring(4) == "00")
        //            {
        //                ktgRow["DenThang"] = Convert.ToInt32(ktgRow["DenThang"].ToString().Substring(0, 4)) - 1;
        //                ktgRow["DenThang"] = ktgRow["DenThang"].ToString() + "12";
        //            }
        //            ktgRow["Mucluong"] = 0;
        //            ktgRow["Hsl"] = 0;
        //            ktgRow["PCCV"] = 0;
        //            ktgRow["PCTN"] = 0;
        //            ktgRow["PCNG"] = 0;
        //            ktgRow["PCKV"] = 0;

        //            ktgRow["pa"] = "OF";
        //            ktgRow["Tendvi"] = "Kh«ng tham gia";
        //            ktgRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(ktgRow["Tuthang"].ToString().Substring(0, 4) + "/" + ktgRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
        //              Convert.ToDateTime(ktgRow["Denthang"].ToString().Substring(0, 4) + "/" + ktgRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
        //            dsQuatrinh.Tables[0].Rows.InsertAt(ktgRow, i + 1);


        //        }
        //    }
        //    namtn = 0;
        //    thangtn = 0;
        //    tuthangxntn = "";
        //    denthangxntn = "";
        //    //dua va dataset dsKQuaTrinh
        //    for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
        //    {
        //        if (dsQuatrinh.Tables[0].Rows[i]["MUCLUONG"].ToString() != "0" || dsQuatrinh.Tables[0].Rows[i]["HSL"].ToString() != "0")
        //        {
        //            if (xacnhan == FlxSobhxh.Rows[k]["xacnhan"].ToString())
        //            {
        //                if (i == 0)
        //                {
        //                    tuthangxntn = dsQuatrinh.Tables[0].Rows[i]["TUTHANG"].ToString();
        //                }
        //                denthangxntn = dsQuatrinh.Tables[0].Rows[i]["Denthang"].ToString();
        //                //chi tinh thoi gian tham gia bhxh
        //                if (dsQuatrinh.Tables[0].Rows[i]["Tendvi"].ToString() != "Kh«ng tham gia")
        //                {
        //                    ModuleBHXH.KhoangThoiGian(ModuleBHXH.FormatThangNam(dsQuatrinh.Tables[0].Rows[i]["TUTHANG"].ToString()),
        //                         ModuleBHXH.FormatThangNam(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"].ToString()), ref namtn, ref thangtn);
        //                }
        //            }
        //            if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"]) >= Convert.ToInt32(thangbd)
        //                       && Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["TUTHANG"]) <= Convert.ToInt32(thangkt))
        //            {
        //                if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["TUTHANG"]) < Convert.ToInt32(thangbd))
        //                {
        //                    dsQuatrinh.Tables[0].Rows[i]["TUTHANG"] = thangbd;
        //                }
        //                if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["DENTHANG"]) > Convert.ToInt32(thangkt))
        //                {
        //                    dsQuatrinh.Tables[0].Rows[i]["DENTHANG"] = thangkt;
        //                }
        //                newRow = dsKQuatrinh.Tables[0].NewRow();
        //                newRow["Maqt"] = thangbd;
        //                newRow["Madvi"] = dsQuatrinh.Tables[0].Rows[i]["Madvi"];
        //                newRow["SOBHXH"] = FlxSobhxh.Rows[k]["SOBHXH"];
        //                newRow["TUTHANG"] =dsQuatrinh.Tables[0].Rows[i]["TUTHANG"].ToString();
        //                newRow["DENTHANG"] = dsQuatrinh.Tables[0].Rows[i]["DENTHANG"].ToString();
        //                newRow["Loaidt"] = dsQuatrinh.Tables[0].Rows[i]["Loaidt"];
        //                newRow["Ma_nte"] = dsQuatrinh.Tables[0].Rows[i]["Ma_nte"];
        //                newRow["CONGVIEC"] = "§ãng b¶o hiÓm thÊt nghiÖp";
        //                newRow["TLBHXH"] = "3";
        //                newRow["mucluong"] = dsQuatrinh.Tables[0].Rows[i]["mucluong"];
        //                newRow["hsl"] = dsQuatrinh.Tables[0].Rows[i]["hsl"];
        //                newRow["PCCV"] = dsQuatrinh.Tables[0].Rows[i]["PCCV"];
        //                newRow["PCTN"] = dsQuatrinh.Tables[0].Rows[i]["PCTN"];
        //                newRow["PCNG"] = dsQuatrinh.Tables[0].Rows[i]["PCNG"];
        //                newRow["PCKV"] = dsQuatrinh.Tables[0].Rows[i]["PCKV"];
        //                newRow["sothang"] = dsQuatrinh.Tables[0].Rows[i]["sothang"];
        //                newRow["pa"] = dsQuatrinh.Tables[0].Rows[i]["pa"];
        //                dsKQuatrinh.Tables[0].Rows.Add(newRow);
        //            }
        //        }
        //    }
        //    dsQuatrinh.Tables[0].Rows.Clear();
        //    if (xacnhan == FlxSobhxh.Rows[k]["xacnhan"].ToString())//truong co chi tiet trong khoang thoi gian 
        //    {
        //        GetDataBHTNOnFlex(xacnhan, namtn, thangtn, tuthangxntn, denthangxntn);
        //    }
        //    thangbd = (Convert.ToInt32(thangkt.Substring(0, 4)) + 1).ToString();
        //    thangbd = thangbd + "01";
        //}

        Boolean checkLastps1(int i, QuatrinhBHXH dsQuatrinh)
        {
            for (int j = i + 1; j < dsQuatrinh.Tables[0].Rows.Count; j++)
            {
                if (dsQuatrinh.Tables[0].Rows[j]["DenThang"].ToString() == "")
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// lay thang da dong het tien tu don vi
        /// </summary>
        /// <param name="madvi"></param>
        /// <param name="sobhxh"></param>
        /// <returns></returns>
        private string GetThangDongTien(string madvi,string sobhxh)
        {
            string strThangDongTien = "", queryString, Maxqt = "", strQuy, strOldQuy;
            double dbtienno = 0,dbtientra = 0,dbtiendk=0,dbtientong=0,mucluong=0;
            string[] arrMaqt = new string[0];
            string[] arrLoaiHS = new string[0];
            double[] arrTienthang = new double[3];
            Boolean Flag=false;// kiem tra xem qui do da quyet toan chua
            int i=0,inttam = 0;
            int sochay;
            SqlCommand command;
            SqlDataReader reader;
            //get max qua trinh
            //queryString = "exec sp_executesql N'SELECT TOP 1 Maqt, Madvi FROM HSC47_DTL "
            //+ " WHERE Sobhxh=@P1  ORDER BY Maqt DESC', "
            //+ " N'@P1 varchar(10)', '" + sobhxh + "'";

            queryString = "exec sp_executesql N'SELECT MAX(Maqt) As Maqt FROM HSC47_HDR WHERE Madvi=@P1 ', "
            + " N'@P1 varchar(7)', '" + madvi + "'";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                command = connection.CreateCommand();
                command.CommandText = queryString;
                connection.Open();
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Maxqt = reader["Maqt"].ToString();
                }
                reader.Close();
                //custom Maxqt
                Maxqt = Maxqt.Substring(0, 6);

                if (Convert.ToInt32(ModuleBHXH.strMonths) == Convert.ToInt32(Maxqt))
                {
                    inttam = Convert.ToInt32(Maxqt) - 1;
                    if (inttam.ToString().Substring(4) == "00")
                    {
                        inttam = Convert.ToInt32(inttam.ToString().Substring(0, 4)) - 1;
                        Maxqt = inttam + "12";
                    }
                    else
                    {
                        Maxqt = Convert.ToString(inttam);
                    }
                }
                //maxqt lon hon thang hien tai --> lay thang hien tai
                else if (Convert.ToInt32(ModuleBHXH.strMonths) < Convert.ToInt32(Maxqt))
                {
                    inttam = Convert.ToInt32(ModuleBHXH.strMonths) - 1;
                    if (inttam.ToString().Substring(4) == "00")
                    {
                        inttam = Convert.ToInt32(inttam.ToString().Substring(0, 4)) - 1;
                        Maxqt = inttam + "12";
                    }
                    else
                    {
                        Maxqt = Convert.ToString(inttam);
                    }
                }
                //lay quy theo thang
                strQuy = GetQuy(Maxqt);
                strOldQuy = (Convert.ToInt16(strQuy) - 1).ToString();
                if (strOldQuy.Substring(4) == "0")
                {
                    strOldQuy = (Convert.ToInt32(strOldQuy.Substring(0, 4)) - 1).ToString() + "4";
                }
                //lay quyet toan thu
                queryString = "exec sp_executesql N'SELECT TOP 1 * FROM HS7BCT"
                    + " WHERE Madvi=@P1  AND Ma_Nte=@P2  AND Quy=@P3 ', "
                    + " N'@P1 varchar(7),@P2 varchar(3),@P3 varchar(5)', "
                    + " '" + madvi + "', 'VND', '" + strQuy + "'";

                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Flag = true;
                }
                reader.Close();
                //kiem tra so cuoi ky co con no khong neu ko no thi lay maxqt

                //get tien dau ki
                queryString = "exec sp_executesql N'SELECT TOP 1 Quy, Ma_Nte, Tamdung, Bhxh_Ck + Bhyt_Ck + Bhtn_Ck + Lai_Ck As Du_Dk, "
                    + " Bhxh_Ck AS Dk_Bhxh, Bhyt_Ck AS Dk_Bhyt, Bhtn_Ck AS Dk_Bhtn, Lai_Ck As Dk_Lai,  "
                    + " Lai1_Ck AS Lai1_Dk, Lai2_Ck AS Lai2_Dk, Lai3_Ck AS Lai3_Dk  "
                    + " FROM S53_HDR WHERE Madvi = @P1  AND Ma_Nte = @P2  AND Quy <= @P3  "
                    + " ORDER BY Quy DESC', N'@P1 varchar(7),@P2 varchar(3),@P3 varchar(5)', "
                    + " '" + madvi + "', 'VND', '" + strOldQuy + "'";

                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    dbtiendk = Convert.ToDouble(reader["Du_DK"]);

                }
                reader.Close();
                dbtienno = dbtiendk;
                if (Flag == true)
                {
                    //lay cac maqt phat sinh trong quy
                    queryString = "exec sp_executesql N'SELECT Madvi, Loaidt, Ma_Nte, MAX(Maqt) AS Maqt "
                    + " FROM HSC47_HDR WHERE Madvi=@P1  AND Quy=@P2 "
                    + " GROUP BY Madvi, Loaidt, Ma_Nte, LEFT(Maqt,6)', N'@P1 varchar(7),@P2 varchar(5)', "
                    + " '" + madvi + "', '" + strQuy + "'";

                    command.CommandText = queryString;
                    reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        arrMaqt = (string[])ModuleBHXH.ResizeArray(arrMaqt, arrMaqt.Length + 1);
                        arrLoaiHS = (string[])ModuleBHXH.ResizeArray(arrLoaiHS, arrLoaiHS.Length + 1);
                        arrMaqt[i] = reader["Maqt"].ToString();
                        arrLoaiHS[i] = reader["Loaidt"].ToString();
                        i++;
                    }
                    reader.Close();
                    //lay tien dong bao hiem cac thang trong quy
                    for (i = 0; i < arrMaqt.Length; i++)
                    {
                        queryString = "exec sp_executesql N'SELECT Madvi, Loaidt, CASE WHEN TygiaTH=0 THEN Ma_Nte ELSE ''VND'' END AS Ma_Nte, "
                        + " LEFT(Maqt,6) AS Thang, Quy, Sld_Ck AS Sld, Sldtn_Ck AS Sldtn, "
                        + " CASE WHEN Loaidt=''HS'' THEN Tql_Ck*Mltt ELSE CASE WHEN TygiaTH=0 THEN Tql_Ck ELSE Tql_Ck*TygiaTH END END AS Tql,"
                        + " CASE WHEN Loaidt=''HS'' THEN Tqlyt_Ck*Mltt ELSE CASE WHEN TygiaTH=0 THEN Tqlyt_Ck ELSE Tqlyt_Ck*TygiaTH END END AS Tqlyt,  "
                        + " CASE WHEN Loaidt=''HS'' THEN Tqltn_Ck*Mltt ELSE CASE WHEN TygiaTH=0 THEN Tqltn_Ck ELSE Tqltn_Ck*TygiaTH END END AS Tqltn,  "
                        + " CASE WHEN TygiaTH=0 THEN Bhxh_Ck ELSE Bhxh_Ck*TygiaTH END AS Pt_Bhxh, "
                        + " CASE WHEN TygiaTH=0 THEN Bhyt_Ck ELSE Bhyt_Ck*TygiaTH END AS Pt_Bhyt, "
                        + " CASE WHEN TygiaTH=0 THEN Bhtn_Ck ELSE Bhtn_Ck*TygiaTH END AS Pt_Bhtn, "
                        + " CASE WHEN TygiaTH=0 THEN Tudv_Ck ELSE Tudv_Ck*TygiaTH END AS Pt_Tudv "
                        + " FROM HSC47_HDR WHERE Madvi=@P1  AND Loaidt=@P2  AND Ma_Nte=@P3  AND Maqt=@P4  ', "
                        + " N'@P1 varchar(7),@P2 varchar(2),@P3 varchar(3),@P4 varchar(8)', "
                        + " '" + madvi + "', '" + arrLoaiHS[i] + "', 'VND', '" + arrMaqt[i] + "'";

                        command.CommandText = queryString;
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            arrTienthang[Convert.ToInt16(reader["Thang"].ToString().Substring(4, 2)) - Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + 2] = Convert.ToDouble(reader["Pt_BHXH"]) + Convert.ToDouble(reader["Pt_BHYT"]) + Convert.ToDouble(reader["Pt_BHTN"]);

                        }
                        reader.Close();
                    }
                    //lay dieu chinh hang thang
                    queryString = "exec sp_executesql N'SELECT Madvi, Loaidt, LEFT(Maqt,6) AS Thang, Quy,"
                     + " CASE WHEN TygiaTH<>0 THEN ''VND'' ELSE CASE WHEN Ma_Nte1<>'''' THEN Ma_Nte1 ELSE Ma_Nte END END AS Ma_Nte, "
                     + " CASE WHEN TygiaTH<>0 THEN ROUND(Bst_Bhxh*TygiaTH,0) ELSE CASE WHEN Ma_Nte1<>'''' THEN Bst_Bhxh1 ELSE Bst_Bhxh END END AS Bst_Bhxh, "
                     + " CASE WHEN TygiaTH<>0 THEN ROUND(Bst_Bhyt*TygiaTH,0) ELSE CASE WHEN Ma_Nte1<>'''' THEN Bst_Bhyt1 ELSE Bst_Bhyt END END AS Bst_Bhyt, "
                     + " CASE WHEN TygiaTH<>0 THEN ROUND(Bst_Bhtn*TygiaTH,0) ELSE CASE WHEN Ma_Nte1<>'''' THEN Bst_Bhtn1 ELSE Bst_Bhtn END END AS Bst_Bhtn, "
                     + " CASE WHEN TygiaTH<>0 THEN ROUND(Bsg_Bhxh*TygiaTH,0) ELSE CASE WHEN Ma_Nte1<>'''' THEN Bsg_Bhxh1 ELSE Bsg_Bhxh END END AS Bsg_Bhxh, "
                     + " CASE WHEN TygiaTH<>0 THEN ROUND(Bsg_Bhyt*TygiaTH,0) ELSE CASE WHEN Ma_Nte1<>'''' THEN Bsg_Bhyt1 ELSE Bsg_Bhyt END END AS Bsg_Bhyt, "
                     + " CASE WHEN TygiaTH<>0 THEN ROUND(Bsg_Bhtn*TygiaTH,0) ELSE CASE WHEN Ma_Nte1<>'''' THEN Bsg_Bhtn1 ELSE Bsg_Bhtn END END AS Bsg_Bhtn  "
                     + " FROM HSC47_HDR WHERE Madvi=@P1  AND Quy=@P2 ', N'@P1 varchar(7),@P2 varchar(5)', '" + madvi + "', '" + strQuy + "'";

                    command.CommandText = queryString;
                    reader = command.ExecuteReader();
                   
                    while (reader.Read())
                    {
                        sochay = Convert.ToInt16(reader["Thang"].ToString().Substring(4, 2)) - Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + 2;
                        arrTienthang[sochay] = arrTienthang[sochay] + Convert.ToDouble(reader["bst_BHXH"]) + Convert.ToDouble(reader["bst_BHYT"]) + Convert.ToDouble(reader["bst_BHTN"])
                            - Convert.ToDouble(reader["bsg_BHXH"]) - Convert.ToDouble(reader["bsg_BHYT"]) - Convert.ToDouble(reader["bsg_BHTN"]);

                    }
                    reader.Close();
                    queryString = " exec sp_executesql N'SELECT Madvi, Loaidt, LEFT(Maqt,6) AS Thang, Quy, "
                    + " CASE WHEN TygiaTH<>0 THEN ''VND'' ELSE CASE WHEN Ma_Nte1<>'''' THEN Ma_Nte1 ELSE Ma_Nte END END AS Ma_Nte, "
                    + " CASE WHEN TygiaTH<>0 THEN ROUND(Bst_Bhxh*TygiaTH,0) ELSE CASE WHEN Ma_Nte1<>'''' THEN Bst_Bhxh1 ELSE Bst_Bhxh END END AS Bst_Bhxh, "
                    + " CASE WHEN TygiaTH<>0 THEN ROUND(Bst_Bhyt*TygiaTH,0) ELSE CASE WHEN Ma_Nte1<>'''' THEN Bst_Bhyt1 ELSE Bst_Bhyt END END AS Bst_Bhyt, "
                    + " CASE WHEN TygiaTH<>0 THEN ROUND(Bsg_Bhxh*TygiaTH,0) ELSE CASE WHEN Ma_Nte1<>'''' THEN Bsg_Bhxh1 ELSE Bsg_Bhxh END END AS Bsg_Bhxh, "
                    + " CASE WHEN TygiaTH<>0 THEN ROUND(Bsg_Bhyt*TygiaTH,0) ELSE CASE WHEN Ma_Nte1<>'''' THEN Bsg_Bhyt1 ELSE Bsg_Bhyt END END AS Bsg_Bhyt "
                    + " FROM HSC47A_HDR WHERE Madvi=@P1  AND Quy=@P2 ', N'@P1 varchar(7),@P2 varchar(5)', "
                    + " '" + madvi + "', '" + strQuy + "'";

                    command.CommandText = queryString;
                    reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        sochay = Convert.ToInt16(reader["Thang"].ToString().Substring(4, 2)) - Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + 2;
                        arrTienthang[sochay] = arrTienthang[sochay] - Convert.ToDouble(reader["Psg_BHXH"]) - Convert.ToDouble(reader["Psg_BHYT"]) - Convert.ToDouble(reader["Psg_BHTN"]);

                    }
                    reader.Close();
                    queryString = " exec sp_executesql N'SELECT Madvi, LEFT(Maqt,6) AS Thang, Quy, ''VND'' As Ma_Nte, "
                    + " SUM(Bsg_Bhxh) As Bsg_Bhxh  FROM HSODTS WHERE Madvi=@P1  AND Quy=@P2  "
                    + " GROUP BY Madvi, LEFT(Maqt,6), Quy', N'@P1 varchar(7),@P2 varchar(5)', '" + madvi + "', '" + strQuy + "'";

                    command.CommandText = queryString;
                    reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        sochay = Convert.ToInt16(reader["Thang"].ToString().Substring(4, 2)) - Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + 2;
                        arrTienthang[sochay] = arrTienthang[sochay] - Convert.ToDouble(reader["Psg_BHXH"]);

                    }
                    reader.Close();
                }
                else // truong hơp chua quyet toan
                {
                    //set cac thang trong quy
                    for (i = 2; i >= 0; i--)
                    {
                        arrMaqt = (string[])ModuleBHXH.ResizeArray(arrMaqt, arrMaqt.Length + 1);
                        arrLoaiHS = (string[])ModuleBHXH.ResizeArray(arrLoaiHS, arrLoaiHS.Length + 1);
                        arrMaqt[2-i] = strQuy.Substring(0,4) + String.Format("{0:00}",(Convert.ToInt16(strQuy.Substring(4))*3 - i));
                        arrLoaiHS[2-i] = "VND";
                    }
                    for (i = 0; i < arrMaqt.Length; i++)
                    {
                        //muc luong trong thang
                        queryString = "exec sp_executesql N'SELECT TOP 1 Mucluong FROM DMLUONG WHERE Thang <= @P1 "
                        + " ORDER BY Thang DESC', N'@P1 varchar(6)', '" + arrMaqt[i] + "'";
                        command.CommandText = queryString;
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            mucluong = Convert.ToDouble(reader["Mucluong"]);
                           
                        }
                        reader.Close();
                        //so tien dong bhxh trong thang truong hop dong he so
                        queryString = "exec sp_executesql N'SELECT TOP 1 Madvi, Ma_Nte, @P1  As Thang, @P2  As Quy, Maqt, Sld_Ck As Sld, Sldtn_Ck As Sldtn,"
                        + " Tql_Ck As Tql, Tqlyt_Ck As Tqlyt, Tqltn_Ck As Tqltn,  Tql_Ck*0 As Pt_Bhxh, Tql_Ck*0 As Pt_Bhyt, Tql_Ck*0 As Pt_Bhtn,"
                        + " Tql_Ck*0 As Pt_Tudv  FROM HSC47_HDR WHERE Madvi=@P3  AND Loaidt=''HS'' AND Ma_Nte=@P4  AND LEFT(Maqt,6)<=@P5 "
                        + " ORDER BY Maqt DESC ', N'@P1 varchar(6),@P2 varchar(5),@P3 varchar(7),@P4 varchar(3),@P5 varchar(6)', '" + arrMaqt[i] + "',"
                        + " '" + strQuy + "', '" + madvi + "', '" + arrLoaiHS[i] + "', '" + arrMaqt[i] + "'";
                                 
                        command.CommandText = queryString;
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            arrTienthang[Convert.ToInt16(reader["Thang"].ToString().Substring(4, 2)) - Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + 2] = 
                                (Convert.ToDouble(reader["Pt_BHXH"]) + Convert.ToDouble(reader["Pt_BHYT"]) + Convert.ToDouble(reader["Pt_BHTN"]))*mucluong;

                        }
                        reader.Close();
                        //so tien dong bhxh trong thang truong hop dong bang tien
                        queryString = "exec sp_executesql N'SELECT TOP 1 Madvi, Ma_Nte, @P1  As Thang, @P2  As Quy, Maqt, Sld_Ck As Sld, Sldtn_Ck As Sldtn,"
                        + " Tql_Ck As Tql, Tqlyt_Ck As Tqlyt, Tqltn_Ck As Tqltn,  Bhxh_Ck As Pt_Bhxh, Bhyt_Ck As Pt_Bhyt, Bhtn_Ck As Pt_Bhtn, "
                        + " Tudv_Ck As Pt_Tudv  "
                        + " FROM HSC47_HDR WHERE Madvi=@P3  AND Loaidt=''ML'' AND Ma_Nte=@P4  AND LEFT(Maqt,6)<=@P5  ORDER BY Maqt DESC', "
                        + " N'@P1 varchar(6),@P2 varchar(5),@P3 varchar(7),@P4 varchar(3),@P5 varchar(6)', "
                        + "'" + arrMaqt[i] + "', '" + strQuy + "', '" + madvi + "', 'VND', '" + arrMaqt[i] + "'";

                        command.CommandText = queryString;
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            arrTienthang[Convert.ToInt16(reader["Thang"].ToString().Substring(4, 2)) - Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + 2] =
                                (Convert.ToDouble(reader["Pt_BHXH"]) + Convert.ToDouble(reader["Pt_BHYT"]) + Convert.ToDouble(reader["Pt_BHTN"]));

                        }
                        reader.Close();
                        //dieu chinh tang giam
                        queryString = "exec sp_executesql N'SELECT Madvi, LEFT(Maqt,6) AS Thang, Quy,"
                        + " CASE WHEN TygiaTH<>0 THEN ''VND'' ELSE CASE WHEN Ma_Nte1<>'''' THEN Ma_Nte1 ELSE Ma_Nte END END AS Ma_Nte, "
                        + " CASE WHEN TygiaTH<>0 THEN ROUND(Bst_Bhxh*TygiaTH,0) "
                        + " ELSE CASE WHEN Ma_Nte1<>'''' THEN Bst_Bhxh1 ELSE Bst_Bhxh END END AS Bst_Bhxh, "
                        + " CASE WHEN TygiaTH<>0 THEN ROUND(Bst_Bhyt*TygiaTH,0) "
                        + " ELSE CASE WHEN Ma_Nte1<>'''' THEN Bst_Bhyt1 ELSE Bst_Bhyt END END AS Bst_Bhyt, "
                        + " CASE WHEN TygiaTH<>0 THEN ROUND(Bst_Bhtn*TygiaTH,0) "
                        + " ELSE CASE WHEN Ma_Nte1<>'''' THEN Bst_Bhtn1 ELSE Bst_Bhtn END END AS Bst_Bhtn, "
                        + " CASE WHEN TygiaTH<>0 THEN ROUND(Bsg_Bhxh*TygiaTH,0) "
                        + " ELSE CASE WHEN Ma_Nte1<>'''' THEN Bsg_Bhxh1 ELSE Bsg_Bhxh END END AS Bsg_Bhxh, "
                        + " CASE WHEN TygiaTH<>0 THEN ROUND(Bsg_Bhyt*TygiaTH,0) "
                        + " ELSE CASE WHEN Ma_Nte1<>'''' THEN Bsg_Bhyt1 ELSE Bsg_Bhyt END END AS Bsg_Bhyt, "
                        + " CASE WHEN TygiaTH<>0 THEN ROUND(Bsg_Bhtn*TygiaTH,0) "
                        + " ELSE CASE WHEN Ma_Nte1<>'''' THEN Bsg_Bhtn1 ELSE Bsg_Bhtn END END AS Bsg_Bhtn  "
                        + " FROM HSC47_HDR WHERE Madvi=@P1  AND Ma_Nte=@P2  AND LEFT(Maqt,6)=@P3 ', "
                        + " N'@P1 varchar(7),@P2 varchar(3),@P3 varchar(6)', '" + madvi + "', 'VND', '" + arrMaqt[i] + "'";
                        command.CommandText = queryString;
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            sochay = Convert.ToInt16(reader["Thang"].ToString().Substring(4, 2)) - Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + 2;
                            arrTienthang[sochay] = arrTienthang[sochay] + Convert.ToDouble(reader["bst_BHXH"]) + Convert.ToDouble(reader["bst_BHYT"]) + Convert.ToDouble(reader["bst_BHTN"])
                                - Convert.ToDouble(reader["bsg_BHXH"]) - Convert.ToDouble(reader["bsg_BHYT"]) - Convert.ToDouble(reader["bsg_BHTN"]);

                        }
                        reader.Close();
                        //tinh giam
                        queryString = " exec sp_executesql N'SELECT Madvi, LEFT(Maqt,6) AS Thang, Quy, ''VND'' As Ma_Nte, SUM(Bsg_Bhxh) As Bsg_Bhxh  "
                        + " FROM HSODTS WHERE Madvi=@P1  AND LEFT(Maqt,6)=@P2  GROUP BY Madvi, LEFT(Maqt,6), Quy', "
                        + " N'@P1 varchar(7),@P2 varchar(6)', '" + madvi + "', '" + arrMaqt[i] + "'";
                        command.CommandText = queryString;
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            sochay = Convert.ToInt16(reader["Thang"].ToString().Substring(4, 2)) - Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + 2;
                            arrTienthang[sochay] = arrTienthang[sochay] - Convert.ToDouble(reader["Psg_BHXH"]);

                        }
                        reader.Close();
                    }

                }
                queryString = " exec sp_executesql N'SELECT Madvi, Thang,  SUM((DcPt_Bhxh - Pt_Bhxh) + "
                + " (DcBst_Bhxh - Bst_Bhxh) - (DcBsg_Bhxh - Bsg_Bhxh)) As Dc01_Bhxh,  "
                + " SUM((DcPt_Bhyt - Pt_Bhyt) + (DcBst_Bhyt - Bst_Bhyt) - (DcBsg_Bhyt - Bsg_Bhyt)) As Dc01_Bhyt,"
                + " SUM((DcPt_Bhtn - Pt_Bhtn) + (DcBst_Bhtn - Bst_Bhtn) - (DcBsg_Bhtn - Bsg_Bhtn)) As Dc01_Bhtn  "
                + " FROM S53_DC WHERE Madvi = @P1  AND Ma_Nte = @P2  AND Quy = @P3  "
                + " GROUP BY Madvi, Thang', N'@P1 varchar(7),@P2 varchar(3),@P3 varchar(5)', "
                + " '" + madvi + "', 'VND', '" + strQuy + " '";

                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    sochay = Convert.ToInt16(reader["Thang"].ToString().Substring(4, 2)) - Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + 2;
                    arrTienthang[sochay] = arrTienthang[sochay] + Convert.ToDouble(reader["DC01_BHXH"]) + Convert.ToDouble(reader["DC01_BHYT"]) + Convert.ToDouble(reader["DC01_BHTN"]);

                }
                reader.Close();
                //ton don vi nop
                queryString = " exec sp_executesql N'SELECT *, SPACE(1) As Loai, ''1'' As Loai1  "
                + " FROM UNC WHERE Madvi = @P1  AND Ma_Nte = @P2  AND Quy = @P3  ', "
                + " N'@P1 varchar(7),@P2 varchar(3),@P3 varchar(5)', "
                + " '" + madvi + "', 'VND', '" + strQuy + "'";
                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    dbtientra = dbtientra + Convert.ToDouble(reader["Tien_VND"]);

                }
                reader.Close();
                //tien tra 2%
                queryString = " exec sp_executesql N'SELECT *, SPACE(1) As Loai, ''2'' As Loai1"
                + " FROM QTC WHERE Madvi = @P1  AND Ma_Nte = @P2  AND Quy = @P3  ',"
                + " N'@P1 varchar(7),@P2 varchar(3),@P3 varchar(5)', "
                + " '" + madvi + "', 'VND', '" + strQuy + "'";
                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    sochay = Convert.ToInt16(reader["Thang"].ToString().Substring(4, 2)) - Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + 2;
                    arrTienthang[sochay] = arrTienthang[sochay] - Convert.ToDouble(reader["Tien_VND"]);

                }
                reader.Close();
                //tien tra lai
                queryString = " exec sp_executesql N'SELECT Madvi, Ma_Nte, Thangnam As Thang, "
                + " SUM(TG_PS) As Noqh, SUM(Lai1_Ps+Lai2_Ps+Lai3_Ps+Lai4_Ps) As Laiqh,"
                + " SUM(CASE WHEN Dc_Lai_Dk > 0 THEN Dc_Lai_Dk ELSE 0 END) As DcBst_Lai,"
                + " SUM(CASE WHEN Dc_Lai_Dk < 0 THEN ABS(Dc_Lai_Dk) ELSE 0 END) As DcBsg_Lai, "
                + " SUM(Lai_Tra) As Dt_Lai, ''1'' As Loai,  SUM(Lai1_Ps+Lai3_Ps) As Lai1_Ps,"
                + " SUM(Lai2_Ps) As Lai2_Ps, SUM(Lai4_Ps) As Lai3_Ps,  SUM(Lai1_Dc) As Lai1_Dc, "
                + " SUM(Lai2_Dc) As Lai2_Dc, SUM(Lai3_Dc) As Lai3_Dc,  SUM(Lai1_Dt) As Lai1_Dt, "
                + " SUM(Lai2_Dt) As Lai2_Dt, SUM(Lai3_Dt) As Lai3_Dt"
                + " FROM HSLAI WHERE Madvi = @P1  AND Ma_Nte = @P2  AND Quy = @P3  "
                + " GROUP BY Madvi, Ma_Nte, Thangnam', N'@P1 varchar(7),@P2 varchar(3),@P3 varchar(5)', "
                + " '" + madvi + "', 'VND', '" + strQuy + "'";
                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    sochay = Convert.ToInt16(reader["Thang"].ToString().Substring(4, 2)) - Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + 2;
                    arrTienthang[sochay] = arrTienthang[sochay] + Convert.ToDouble(reader["laiqh"]);

                }
                reader.Close();
                //tien nop hon thwoi diem hien tai
                queryString = " exec sp_executesql N'SELECT ISNULL(SUM(Tien_VND),0) AS Tien_VND, ISNULL(SUM(Tien_Nte),0) AS Tien_Nte "
                + " FROM UNC WHERE Madvi = @P1  AND Ma_Nte = @P2  "
                + " AND Thang > @P3  AND Ngay <= @P4 ', "
                + " N'@P1 varchar(7),@P2 varchar(3),@P3 varchar(6),@P4 datetime', "
                + " '" + madvi + "', 'VND', '" + Maxqt + "', '" + ModuleBHXH.strDate + "'";
                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    dbtientra = dbtientra + Convert.ToDouble(reader["Tien_VND"]);

                }
                reader.Close();
                //tien tra lai don vi
                queryString = " exec sp_executesql N'SELECT ISNULL(SUM(Tien_VND),0) AS Tien_VND, ISNULL(SUM(Tien_Nte),0) AS Tien_Nte FROM QTC "
                + " WHERE Madvi = @P1  AND Ma_Nte = @P2  AND Thang > @P3  AND Ngay <= @P4 ', "
                + " N'@P1 varchar(7),@P2 varchar(3),@P3 varchar(6),@P4 datetime', "
                + " '" + madvi + "', 'VND', '" + Maxqt + "', '" + ModuleBHXH.strDate + "'";
                command.CommandText = queryString;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    dbtientra = dbtientra - Convert.ToDouble(reader["Tien_VND"]);

                }
                reader.Close();
                //tinh toan ra thang dong
                dbtientong = dbtienno + arrTienthang[0] + arrTienthang[1] + arrTienthang[2] - dbtientra;
                if (dbtientong <= 0) //da tra tien het quy
                {
                    strThangDongTien = Maxqt;
                }
                else //chua tra tien het quy
                {
                    for (i = arrTienthang.Length-1; i >=0; i--)
                    {
                        dbtientong = dbtientong - arrTienthang[i];
                        if (dbtientong < 0)
                        {
                            strThangDongTien = Maxqt.Substring(0, 4) + String.Format("{0:00}", 
                                Convert.ToInt16(Convert.ToInt16(strQuy.Substring(4, 1)) * 3 + i - 3));
                            return strThangDongTien;
                        }
                    }

                    strThangDongTien = Maxqt.Substring(0, 4) + String.Format("{0:00}", Convert.ToInt16(Convert.ToInt16(strQuy.Substring(4, 1)) * 3 - 3));
                    if (strThangDongTien.Substring(4) == "00")
                    {

                        strThangDongTien = (Convert.ToInt32(strThangDongTien.Substring(0, 4)) - 1).ToString() + "12";
                    }
                    int intthanghienhanh;
                    while (dbtientong > 0)
                    {

                        queryString = "exec sp_executesql N'SELECT TOP 1 (Pt_Bhxh + Bst_Bhxh - Bsg_Bhxh) AS Pt_Bhxh,"
                        + " (Pt_Bhyt + Bst_Bhyt - Bsg_Bhyt) AS Pt_Bhyt,  (Pt_Bhtn + Bst_Bhtn - Bsg_Bhtn) AS Pt_Bhtn "
                        + " FROM S53_DTL WHERE Madvi=@P1  AND Ma_Nte=@P2  AND Thang =@P3  ', "
                        + " N'@P1 varchar(7),@P2 varchar(3),@P3 varchar(6)', '" + madvi + "', 'VND', '" + strThangDongTien + "'";
                        command.CommandText = queryString;
                        reader = command.ExecuteReader();
                        if (reader.HasRows == true)
                        {
                            reader.Read();
                            dbtientong = dbtientong - Convert.ToDouble(reader["Pt_BHXH"]) - Convert.ToDouble(reader["Pt_BHYT"]) - Convert.ToDouble(reader["Pt_BHTN"]);
                        }
                        else
                        {
                            break;
                        }
                        reader.Close();
                        queryString = "exec sp_executesql N'SELECT Madvi, Thang,  "
                        + " SUM((DcPt_Bhxh - Pt_Bhxh) + (DcBst_Bhxh - Bst_Bhxh) - (DcBsg_Bhxh - Bsg_Bhxh)) As Dc01_Bhxh,"
                        + " SUM((DcPt_Bhyt - Pt_Bhyt) + (DcBst_Bhyt - Bst_Bhyt) - (DcBsg_Bhyt - Bsg_Bhyt)) As Dc01_Bhyt,"
                        + " SUM((DcPt_Bhtn - Pt_Bhtn) + (DcBst_Bhtn - Bst_Bhtn) - (DcBsg_Bhtn - Bsg_Bhtn)) As Dc01_Bhtn  "
                        + " FROM S53_DC WHERE Madvi=@P1  AND Ma_Nte=@P2  AND Thang = @P3  GROUP BY Madvi, Thang', "
                        + " N'@P1 varchar(7),@P2 varchar(3),@P3 varchar(6)', '" + madvi + "', 'VND', '" + strThangDongTien + "'";
                        command.CommandText = queryString;
                        reader = command.ExecuteReader();
                        while (reader.Read())
                        {
                            dbtientong = dbtientong + Convert.ToDouble(reader["dc01_BHXH"]) + Convert.ToDouble(reader["dc01_BHYT"]) + Convert.ToDouble(reader["dc01_BHTN"]);
                        }
                        reader.Close();

                        intthanghienhanh = Convert.ToInt32(strThangDongTien) - 1;
                        if (intthanghienhanh.ToString().Substring(4) == "00")
                        {
                            intthanghienhanh = Convert.ToInt32(intthanghienhanh.ToString().Substring(0, 4)) - 1;
                            strThangDongTien = intthanghienhanh + "12";
                        }
                        else
                        {
                            strThangDongTien = Convert.ToString(intthanghienhanh);
                        }
                    }

                }
            }
            return strThangDongTien;
        }
        /// <summary>
        /// lay quy tu thang hien tai
        /// </summary>
        /// <param name="Maxqt"></param>
        /// <returns></returns>
        private string GetQuy(string Maxqt)
        {
            string strQuy;
            int intQuy;
            strQuy = Maxqt.Substring(4, 2);
            intQuy = Convert.ToInt16(strQuy);
            switch (intQuy)
            {
                case 1:
                case 2:
                case 3:
                    strQuy = Maxqt.Substring(0,4) + "1";
                    break;
                case 4:
                case 5:
                case 6:
                    strQuy = Maxqt.Substring(0,4) + "2";
                    break;
                case 7:
                case 8:
                case 9:
                    strQuy = Maxqt.Substring(0,4) + "3";
                    break;
                case 10:
                case 11:
                case 12:
                    strQuy = Maxqt.Substring(0,4) + "4";
                    break;
            }
            return strQuy;
        }
        /// <summary>
        /// insert row vao qua trinh tai vi tri i
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        /// <param name="newRow"></param>
        /// <param name="denthang"></param>
        /// <param name="i"></param>
        private void insertNewRow(QuatrinhBHXH dsQuatrinh, DataRow newRow, int denthang, int i)
        {
            newRow["denthang"] = denthang - 1;
            if (newRow["denthang"].ToString().Substring(4) == "00")
            {
                newRow["denthang"] = Convert.ToInt32(newRow["denthang"].ToString().Substring(0, 4)) - 1;
                newRow["denthang"] = newRow["denthang"].ToString() + "12";
            }
            //tu thang lon hon den thang xoa dong
            if (Convert.ToInt32(newRow["tuthang"]) <= Convert.ToInt32(newRow["denThang"]))
            {
                newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                               Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);

            }

        }
        /// <summary>
        /// update qua trinh giam theo tham so den thang
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        /// <param name="currentRow"></param>
        /// <param name="denthang"></param>
        private void UpdateCurrentRowGiam(QuatrinhBHXH dsQuatrinh, DataRow currentRow, int denthang)
        {
            currentRow["denthang"] = denthang - 1;
            if (currentRow["denthang"].ToString().Substring(4) == "00")
            {
                currentRow["denthang"] = Convert.ToInt32(currentRow["denthang"].ToString().Substring(0, 4)) - 1;
                currentRow["denthang"] = currentRow["denthang"].ToString() + "12";
            }
            //tu thang lon hon den thang xong dong
            if (Convert.ToInt32(currentRow["tuthang"]) > Convert.ToInt32(currentRow["denThang"]))
            {
                currentRow.Delete();

            }
            else //tinh lai khoang thoi gian
            {
                currentRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(currentRow["Tuthang"].ToString().Substring(0, 4) + "/" + currentRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(currentRow["Denthang"].ToString().Substring(0, 4) + "/" + currentRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
            }
        }
        /// <summary>
        /// update qua trinh tang theo tham so tu thang
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        /// <param name="currentRow"></param>
        /// <param name="tuthang"></param>
        private void UpdateCurrentRowTang(QuatrinhBHXH dsQuatrinh, DataRow currentRow, int tuthang)
        {
            currentRow["Tuthang"] = tuthang + 1;
            if (currentRow["Tuthang"].ToString().Substring(4) == "13")
            {
                currentRow["Tuthang"] = Convert.ToInt32(currentRow["Tuthang"].ToString().Substring(0, 4)) + 1;
                currentRow["Tuthang"] = currentRow["Tuthang"].ToString() + "01";
            }
            //tu thang lon hon den thang xong dong
            if (Convert.ToInt32(currentRow["tuthang"]) > Convert.ToInt32(currentRow["denThang"]))
            {
                currentRow.Delete();

            }
            else //tinh lai khoang thoi gian
            {
                currentRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(currentRow["Tuthang"].ToString().Substring(0, 4) + "/" + currentRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                                Convert.ToDateTime(currentRow["Denthang"].ToString().Substring(0, 4) + "/" + currentRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
            }
        }
        /// <summary>
        /// truong hop phuong an DC
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        /// <param name="newRow"></param>
        private void PA_DC(QuatrinhBHXH dsQuatrinh, DataRow newRow)
        {
            DataRow currentRow;
            for (int i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {
                currentRow = dsQuatrinh.Tables[0].Rows[i];
                if (currentRow["Madvi"].ToString() == newRow["Madvi"].ToString())
                {
                    //den thang dong moi < tu thang dong duyet
                    if (Convert.ToInt32(newRow["Denthang"].ToString()) < Convert.ToInt32(currentRow["Tuthang"]))
                    {
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        break;
                    }
                    //den thang dong moi = tu thang dong duyet
                    else if (Convert.ToInt32(newRow["Denthang"].ToString()) == Convert.ToInt32(currentRow["Tuthang"]))
                    {
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(currentRow["Tuthang"]));
                        break;

                    }// tu thang current row <den thang newrow < den thang current row, tu thang new row<= tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"].ToString()) > Convert.ToInt32(currentRow["Tuthang"])
                        && Convert.ToInt32(newRow["Denthang"].ToString()) < Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"].ToString()) <= Convert.ToInt32(currentRow["tuthang"]))
                    {

                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                        break;
                    }
                    // den thang newrow = den thang current row, tu thang new row< tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"])
                       && Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["tuthang"]))
                    {

                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        currentRow.Delete();
                        break;

                    }
                    // den thang newrow > den thang current row, tu thang new row< tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Denthang"])
                       && Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["tuthang"]))
                    {

                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        currentRow.Delete();
                        i = i + 1;
                        for (int j = i; j < dsQuatrinh.Tables[0].Rows.Count; j++)
                        {
                            currentRow = dsQuatrinh.Tables[0].Rows[j];
                            //den thang newrow < den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) < Convert.ToInt32(currentRow["Denthang"]))
                            {
                                UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                                break;
                            }
                            //den thang newrow == den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"]))
                            {
                                currentRow.Delete();
                                break;
                            }
                            //den thang newrow > den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Denthang"]))
                            {
                                currentRow.Delete();
                                j--;
                            }

                        }
                        break;
                    }// tu thang current row <den thang newrow < den thang current row, tu thang new row > tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Tuthang"])
                        && Convert.ToInt32(newRow["Denthang"]) < Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["tuthang"]))
                    {
                        DataRow newRow1 = dsQuatrinh.Tables[0].NewRow();
                        newRow1.ItemArray = currentRow.ItemArray;
                        insertNewRow(dsQuatrinh, newRow1, Convert.ToInt32(newRow["Tuthang"]), i);
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                        break;
                    }
                    // tu thang current row <den thang newrow < den thang current row, tu thang new row > tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["tuthang"]))
                    {
                        UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);

                        break;
                    }
                    // tu thang current row <den thang newrow < den thang current row, tu thang new row > tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"].ToString()) > Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"].ToString()) > Convert.ToInt32(currentRow["tuthang"])
                        && Convert.ToInt32(newRow["Tuthang"].ToString()) < Convert.ToInt32(currentRow["Denthang"]))
                    {
                        UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        i = i + 2;
                        for (int j = i; j < dsQuatrinh.Tables[0].Rows.Count; j++)
                        {
                            currentRow = dsQuatrinh.Tables[0].Rows[j];
                            //den thang newrow < den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) < Convert.ToInt32(currentRow["Denthang"]))
                            {
                                UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                                break;
                            }
                            //den thang newrow == den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"]))
                            {
                                currentRow.Delete();
                                break;
                            }
                            //den thang newrow > den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Denthang"]))
                            {
                                currentRow.Delete();
                                j--;
                            }
                        }
                        break;
                    }
                    //den thang newrow == den thang current row, tu thang new row == tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"].ToString()) == Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"].ToString()) == Convert.ToInt32(currentRow["Tuthang"]))
                    {

                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        currentRow.Delete();
                        break;
                    }
                    //den thang newrow == den thang current row, tu thang new row == den thang current row
                    else if (Convert.ToInt32(newRow["Denthang"].ToString()) == Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"].ToString()) == Convert.ToInt32(currentRow["Denthang"]))
                    {
                        UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        break;
                    }
                }

            }

        }
        /// <summary>
        /// Truong hop phuong an SB(Pending)
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        /// <param name="newRow"></param>
        private void PA_SB(QuatrinhBHXH dsQuatrinh, DataRow newRow)
        {
            DataRow currentRow;
            for (int i = dsQuatrinh.Tables[0].Rows.Count - 1; i >= 0; i--)
            {
                currentRow = dsQuatrinh.Tables[0].Rows[i];
                if (currentRow["Madvi"].ToString() == newRow["Madvi"].ToString())
                {
                    if (currentRow["loaips"].ToString() == "2") // truong hop doan xet co ps = 2
                    {
                        //vi tri nam giua doan dang duyet
                        //cat bo doan giua xet
                        if (Convert.ToInt32(newRow["Denthang"]) < Convert.ToInt32(currentRow["Denthang"]) &&
                            Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["Tuthang"]))
                        {
                            DataRow newRow1 = dsQuatrinh.Tables[0].NewRow();
                            newRow1.ItemArray = currentRow.ItemArray;
                            insertNewRow(dsQuatrinh, newRow1, Convert.ToInt32(newRow["Tuthang"]), i);
                            UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                            break;
                        }
                        else if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"]) &&
                        Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["Tuthang"]))
                        {
                            UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                            break;
                        }
                        else if (Convert.ToInt32(newRow["Denthang"]) < Convert.ToInt32(currentRow["Denthang"]) &&
                        Convert.ToInt32(newRow["Tuthang"]) == Convert.ToInt32(currentRow["Tuthang"]))
                        {
                            UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                            break;
                        }
                        else if (Convert.ToInt32(newRow["Denthang"]) >= Convert.ToInt32(currentRow["Denthang"]) &&
                        Convert.ToInt32(newRow["Tuthang"]) >= Convert.ToInt32(currentRow["Tuthang"]))
                        {
                            currentRow.Delete();
                            break;
                        }
                        else if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Denthang"]) &&
                        Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Tuthang"]) &&
                        Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["Tuthang"]))
                        {
                            UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                            for (int j = i - 1; j < 0; j--)
                            {
                                currentRow = dsQuatrinh.Tables[0].Rows[j];
                                if (Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["Tuthang"]))
                                {
                                    currentRow.Delete();
                                }
                                else if (Convert.ToInt32(newRow["Tuthang"]) == Convert.ToInt32(currentRow["Tuthang"]))
                                {
                                    currentRow.Delete();
                                    break;
                                }
                                else
                                {
                                    UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                                    break;
                                }
                            }
                            break;
                        }
                        else if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Denthang"]) &&
                        Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["Tuthang"]) &&
                        Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["Denthang"]))
                        {
                            currentRow.Delete();
                            break;
                        }
                    }
                    else // truong hop doan xet co ps = 1
                    {
                        if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["maqt"]))
                        {
                            currentRow["maqt"] = Convert.ToInt32(newRow["Denthang"]) + 1; //tang maqt len 1 thang
                            if (currentRow["maqt"].ToString().Substring(4) == "13")
                            {
                                currentRow["maqt"] = Convert.ToInt32(currentRow["maqt"].ToString().Substring(0, 4)) + 1;
                                currentRow["maqt"] = currentRow["maqt"].ToString() + "01";
                            }
                            if (i >= 0 && i < dsQuatrinh.Tables[0].Rows.Count - 1) // xet xem maqt co hop len ko neu ko xoa
                            {
                                if (Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i + 1]["maqt"]) < Convert.ToInt32(currentRow["maqt"]))
                                {
                                    currentRow.Delete();
                                }
                            }

                        }
                        else if (Convert.ToInt32(newRow["Tuthang"]) == Convert.ToInt32(currentRow["maqt"]))
                        {
                            currentRow["maqt"] = Convert.ToInt32(newRow["Denthang"]) + 1;
                            if (currentRow["maqt"].ToString().Substring(4) == "13")
                            {
                                currentRow["maqt"] = Convert.ToInt32(currentRow["maqt"].ToString().Substring(0, 4)) + 1;
                                currentRow["maqt"] = currentRow["maqt"].ToString() + "01";
                            }
                            if (i >= 0 && Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i + 1]["maqt"]) < Convert.ToInt32(currentRow["maqt"]))
                            {
                                currentRow.Delete();
                            }
                            break;
                        }
                        if (i == 0)
                        {
                            newRow["PA"] = "OF";
                            dsQuatrinh.Tables[0].Rows.Add(newRow);
                        }

                    }
                }
            }

        }
        /// <summary>
        /// truong hop phuong an CD
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        /// <param name="newRow"></param>
        private void PA_CD(QuatrinhBHXH dsQuatrinh, DataRow newRow)
        {

            DataRow currentRow;
            for (int i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {
                currentRow = dsQuatrinh.Tables[0].Rows[i];
                if (currentRow["Madvi"].ToString() == newRow["Madvi"].ToString())
                {
                    newRow["Mucluong"] = currentRow["Mucluong"];
                    newRow["Hsl"] = currentRow["Hsl"];
                    newRow["PCCV"] = currentRow["PCCV"];
                    newRow["PCTN"] = currentRow["PCTN"];
                    newRow["PCNG"] = currentRow["PCNG"];
                    //Tu thang 12/2007 khong co pc4
                    newRow["PCKV"] = 0;
                    //den thang dong moi = tu thang dong duyet
                    if (Convert.ToInt32(newRow["Denthang"].ToString()) == Convert.ToInt32(currentRow["Tuthang"]))
                    {


                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(currentRow["Tuthang"]));
                        break;

                    }// tu thang current row <den thang newrow < den thang current row, tu thang new row<= tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"].ToString()) > Convert.ToInt32(currentRow["Tuthang"])
                        && Convert.ToInt32(newRow["Denthang"].ToString()) < Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"].ToString()) <= Convert.ToInt32(currentRow["tuthang"]))
                    {

                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                        break;
                    }
                    // den thang newrow = den thang current row, tu thang new row< tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"])
                       && Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["tuthang"]))
                    {

                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        currentRow.Delete();
                        break;

                    }
                    // den thang newrow > den thang current row, tu thang new row< tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Denthang"])
                       && Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["tuthang"]))
                    {

                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        currentRow.Delete();
                        i = i - 1;
                        for (int j = i + 1; j < dsQuatrinh.Tables[0].Rows.Count; j++)
                        {
                            currentRow = dsQuatrinh.Tables[0].Rows[j];
                            //den thang newrow < den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) < Convert.ToInt32(currentRow["Denthang"]))
                            {
                                UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                                break;
                            }
                            //den thang newrow == den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"]))
                            {
                                currentRow.Delete();
                                break;
                            }
                            //den thang newrow > den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Denthang"]))
                            {
                                currentRow.Delete();
                                j--;
                            }
                        }
                    }// tu thang current row <den thang newrow < den thang current row, tu thang new row > tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Tuthang"])
                        && Convert.ToInt32(newRow["Denthang"]) < Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["tuthang"]))
                    {
                        DataRow newRow1 = dsQuatrinh.Tables[0].NewRow();
                        newRow1.ItemArray = currentRow.ItemArray;
                        insertNewRow(dsQuatrinh, newRow1, Convert.ToInt32(newRow["Tuthang"]), i);
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                        break;
                    }
                    // tu thang current row <den thang newrow < den thang current row, tu thang new row > tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["tuthang"]))
                    {
                        UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);

                        break;
                    }
                    // den thang newrow > den thang current row, denthang>tu thang new row > tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"].ToString()) > Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"].ToString()) >= Convert.ToInt32(currentRow["tuthang"])
                        && Convert.ToInt32(newRow["Tuthang"].ToString()) <= Convert.ToInt32(currentRow["Denthang"]))
                    {
                        UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        i = i + 1;
                        for (int j = i + 1; j < dsQuatrinh.Tables[0].Rows.Count; j++)
                        {
                            currentRow = dsQuatrinh.Tables[0].Rows[j];
                            //den thang newrow < den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) < Convert.ToInt32(currentRow["Denthang"]))
                            {
                                UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                                break;
                            }
                            //den thang newrow == den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"]))
                            {
                                currentRow.Delete();
                                break;
                            }
                            //den thang newrow > den thang current row
                            if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Denthang"]))
                            {
                                currentRow.Delete();
                                j--;
                            }
                        }
                        break;
                    }
                    //den thang newrow == den thang current row, tu thang new row == tu thang current row
                    else if (Convert.ToInt32(newRow["Denthang"].ToString()) == Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"].ToString()) == Convert.ToInt32(currentRow["Tuthang"]))
                    {

                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        currentRow.Delete();
                        break;
                    }
                    //den thang newrow == den thang current row, tu thang new row == den thang current row
                    else if (Convert.ToInt32(newRow["Denthang"].ToString()) == Convert.ToInt32(currentRow["Denthang"])
                        && Convert.ToInt32(newRow["Tuthang"].ToString()) == Convert.ToInt32(currentRow["Denthang"]))
                    {
                        UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        break;
                    }
                }
            }


        }
        /// <summary>
        /// Phuong an tang moi hay dieu chinh muc luong voi phuong an 1
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        /// <param name="newRow"></param>
        private void PA_GD_01(QuatrinhBHXH dsQuatrinh, DataRow newRow, string Maxqt)
        {
            DataRow currentRow = null;
            int i;
            //sap xep theo maqt
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {
                currentRow = dsQuatrinh.Tables[0].Rows[i];
                if (currentRow["Madvi"].ToString() == newRow["Madvi"].ToString())
                {
                    if (Convert.ToInt32(newRow["Tuthang"]) == Convert.ToInt32(currentRow["Tuthang"]))
                    {
                        newRow["Denthang"] = currentRow["Denthang"];
                        newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        dsQuatrinh.Tables[0].Rows.RemoveAt(i + 1);
                        break;
                    }
                    else if (Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["Tuthang"])
                        && Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["Denthang"]))
                    {
                        newRow["Denthang"] = currentRow["Denthang"];
                        UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                        newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        break;
                    }
                    else if (Convert.ToInt32(newRow["Tuthang"]) == Convert.ToInt32(currentRow["Denthang"]))
                    {
                        UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                        newRow["Denthang"] = newRow["Tuthang"];
                        newRow["Sothang"] = 0;
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        break;
                    }
                }

            }
            if (dsQuatrinh.Tables[0].Rows.Count == 0) // dong dau tien trong dataset
            {
                newRow["denthang"] = Maxqt;
                newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                    Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                dsQuatrinh.Tables[0].Rows.Add(newRow);
            }
            
        }
        /// <summary>
        /// Phuong an tang moi hay dieu chinh muc luong voi phuong an 1
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        /// <param name="newRow"></param>
        private void PA_TM_01(QuatrinhBHXH dsQuatrinh, DataRow newRow,string Maxqt)
        {
            DataRow currentRow = null;
            int i;
            //sap xep theo maqt
            for (i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {
                
                    currentRow = dsQuatrinh.Tables[0].Rows[i];
                    if (currentRow["Madvi"].ToString() == newRow["Madvi"].ToString())
                    {
                    //nho hon thang dang duyet
                    if (Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["Tuthang"]))
                    {
                        insertNewRow(dsQuatrinh, newRow, Convert.ToInt32(currentRow["Tuthang"]), i);
                        break;
                    }
                    else if (Convert.ToInt32(newRow["Tuthang"]) == Convert.ToInt32(currentRow["Tuthang"]))
                    {
                        newRow["Denthang"] = currentRow["Denthang"];
                        newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                        dsQuatrinh.Tables[0].Rows.RemoveAt(i + 1);
                        break;
                    }
                    else if (Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["Tuthang"])
                        && Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["Denthang"]))
                    {
                        newRow["Denthang"] = currentRow["Denthang"];
                        UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                        newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                        Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        break;
                    }
                    else if (Convert.ToInt32(newRow["Tuthang"]) == Convert.ToInt32(currentRow["Denthang"]))
                    {
                        UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                        newRow["Denthang"] = newRow["Tuthang"];
                        newRow["Sothang"] = 0;
                        dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                        break;
                    }
                }
                
            }
            if (dsQuatrinh.Tables[0].Rows.Count == 0) // dong dau tien trong dataset
            {
                newRow["denthang"] = Maxqt;
                newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                    Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                dsQuatrinh.Tables[0].Rows.Add(newRow);
            }
            else if (dsQuatrinh.Tables[0].Rows.Count == i) //dong cuoi dung trong dataset
            {
                dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"] = Convert.ToInt32(newRow["Tuthang"]) - 1;
                if (dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"].ToString().Substring(4) == "00")
                {
                    dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"] = Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"].ToString().Substring(0, 4)) - 1;
                    dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"] = dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"].ToString() + "12";
                }
                dsQuatrinh.Tables[0].Rows[i - 1]["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i - 1]["Tuthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i - 1]["Tuthang"].ToString().Substring(4, 2) + "/01"),
                    Convert.ToDateTime(dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"].ToString().Substring(0, 4) + "/" + dsQuatrinh.Tables[0].Rows[i - 1]["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
                if (Convert.ToInt32(newRow["tuthang"]) <= Convert.ToInt32(Maxqt))
                {
                    newRow["Denthang"] = Maxqt;
                    newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
                    Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;

                    dsQuatrinh.Tables[0].Rows.Add(newRow);
                }
            }
        }
        /// <summary>
        /// TRUONG HOP PHUONG AN CD
        /// </summary>
        /// <param name="dsQuatrinh"></param>
        /// <param name="newRow"></param>
        private void PA_AD(QuatrinhBHXH dsQuatrinh, DataRow newRow)
        {

            DataRow currentRow;
            for (int i = 0; i < dsQuatrinh.Tables[0].Rows.Count; i++)
            {
                
                    currentRow = dsQuatrinh.Tables[0].Rows[i];
                    if (currentRow["Madvi"].ToString() == newRow["Madvi"].ToString())
                    {
                        newRow["Congviec"] = currentRow["Congviec"];
                        //den thang dong moi < tu thang dong duyet
                        if (Convert.ToInt32(newRow["Denthang"].ToString()) < Convert.ToInt32(currentRow["Tuthang"]))
                        {
                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                            break;
                        }
                        //den thang dong moi = tu thang dong duyet
                        else if (Convert.ToInt32(newRow["Denthang"].ToString()) == Convert.ToInt32(currentRow["Tuthang"]))
                        {


                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                            UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(currentRow["Tuthang"]));
                            break;

                        }// tu thang current row <den thang newrow < den thang current row, tu thang new row<= tu thang current row
                        else if (Convert.ToInt32(newRow["Denthang"].ToString()) > Convert.ToInt32(currentRow["Tuthang"])
                            && Convert.ToInt32(newRow["Denthang"].ToString()) < Convert.ToInt32(currentRow["Denthang"])
                            && Convert.ToInt32(newRow["Tuthang"].ToString()) <= Convert.ToInt32(currentRow["tuthang"]))
                        {

                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                            UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                            break;
                        }
                        // den thang newrow = den thang current row, tu thang new row< tu thang current row
                        else if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"])
                           && Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(currentRow["tuthang"]))
                        {

                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                            currentRow.Delete();
                            break;

                        }
                        // den thang newrow > den thang current row, tu thang new row< tu thang current row
                        else if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["Denthang"])
                           && Convert.ToInt32(newRow["Tuthang"]) < Convert.ToInt32(dsQuatrinh.Tables[0].Rows[i]["tuthang"]))
                        {

                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                            currentRow.Delete();
                            i = i - 1;
                            for (int j = i + 1; j < dsQuatrinh.Tables[0].Rows.Count; j++)
                            {
                                currentRow = dsQuatrinh.Tables[0].Rows[j];
                                //den thang newrow < den thang current row
                                if (Convert.ToInt32(newRow["Denthang"]) < Convert.ToInt32(currentRow["Denthang"]))
                                {
                                    UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                                    break;
                                }
                                //den thang newrow == den thang current row
                                if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"]))
                                {
                                    currentRow.Delete();
                                    break;
                                }
                                //den thang newrow > den thang current row
                                if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Denthang"]))
                                {
                                    currentRow.Delete();
                                    j--;
                                }
                            }
                        }// tu thang current row <den thang newrow < den thang current row, tu thang new row > tu thang current row
                        else if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Tuthang"])
                            && Convert.ToInt32(newRow["Denthang"]) < Convert.ToInt32(currentRow["Denthang"])
                            && Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["tuthang"]))
                        {
                            DataRow newRow1 = dsQuatrinh.Tables[0].NewRow();
                            newRow1.ItemArray = currentRow.ItemArray;
                            insertNewRow(dsQuatrinh, newRow1, Convert.ToInt32(newRow["Tuthang"]), i);
                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                            UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                            break;
                        }
                        // tu thang current row <den thang newrow < den thang current row, tu thang new row > tu thang current row
                        else if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"])
                            && Convert.ToInt32(newRow["Tuthang"]) > Convert.ToInt32(currentRow["tuthang"]))
                        {
                            UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);

                            break;
                        }
                        // den thang newrow > den thang current row, denthang>tu thang new row > tu thang current row
                        else if (Convert.ToInt32(newRow["Denthang"].ToString()) > Convert.ToInt32(currentRow["Denthang"])
                            && Convert.ToInt32(newRow["Tuthang"].ToString()) >= Convert.ToInt32(currentRow["tuthang"])
                            && Convert.ToInt32(newRow["Tuthang"].ToString()) <= Convert.ToInt32(currentRow["Denthang"]))
                        {
                            UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                            i = i + 1;
                            for (int j = i + 1; j < dsQuatrinh.Tables[0].Rows.Count; j++)
                            {
                                currentRow = dsQuatrinh.Tables[0].Rows[j];
                                //den thang newrow < den thang current row
                                if (Convert.ToInt32(newRow["Denthang"]) < Convert.ToInt32(currentRow["Denthang"]))
                                {
                                    UpdateCurrentRowTang(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Denthang"]));
                                    break;
                                }
                                //den thang newrow == den thang current row
                                if (Convert.ToInt32(newRow["Denthang"]) == Convert.ToInt32(currentRow["Denthang"]))
                                {
                                    currentRow.Delete();
                                    break;
                                }
                                //den thang newrow > den thang current row
                                if (Convert.ToInt32(newRow["Denthang"]) > Convert.ToInt32(currentRow["Denthang"]))
                                {
                                    currentRow.Delete();
                                    j--;
                                }
                            }
                            break;
                        }
                        //den thang newrow == den thang current row, tu thang new row == tu thang current row
                        else if (Convert.ToInt32(newRow["Denthang"].ToString()) == Convert.ToInt32(currentRow["Denthang"])
                            && Convert.ToInt32(newRow["Tuthang"].ToString()) == Convert.ToInt32(currentRow["Tuthang"]))
                        {

                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i);
                            currentRow.Delete();
                            break;
                        }
                        //den thang newrow == den thang current row, tu thang new row == den thang current row
                        else if (Convert.ToInt32(newRow["Denthang"].ToString()) == Convert.ToInt32(currentRow["Denthang"])
                            && Convert.ToInt32(newRow["Tuthang"].ToString()) == Convert.ToInt32(currentRow["Denthang"]))
                        {
                            UpdateCurrentRowGiam(dsQuatrinh, currentRow, Convert.ToInt32(newRow["Tuthang"]));
                            dsQuatrinh.Tables[0].Rows.InsertAt(newRow, i + 1);
                            break;
                        }
                    }
            }

        }
        #endregion

        private void btnGhi_Click(object sender, EventArgs e)
        {
            DataRow newRow = null;
            DataRow[] foundRows;


            if (faQuaTrinh.Rows.Count == 1 || flageFlex != 2)
            {
                return;
            }
            if (dtTuThang.Text == "" || dtDenThang.Text == "")
            {
                MessageBox.Show("NhËp tõ th¸ng dÕn th¸ng");
                return;
            }
            if ( Convert.ToInt32(dtDenThang.Text) >= Convert.ToInt32(faQuaTrinh.Rows[1]["TuThang"]))
            {
                MessageBox.Show("Trïng qu¸ tr×nh");
                return;
            }

            newRow = dsKQuatrinh.Tables[0].NewRow();
            newRow["Maqt"] = FlxDetail.Rows[FlxDetail.Selection.TopRow]["tuthang"].ToString();
            newRow["SOBHXH"] = FlxDetail.Rows[FlxDetail.Selection.TopRow]["sobhxh"];
            newRow["Tuthang"] = dtTuThang.Text;
            newRow["DenThang"] = dtDenThang.Text;
            newRow["Mucluong"] = 0;
            newRow["Hsl"] = 0;
            newRow["PCCV"] = 0;
            newRow["PCTN"] = 0;
            newRow["PCNG"] = 0;
            newRow["PCKV"] = 0;
            newRow["TLBHXH"] = 0;
            newRow["pa"] = "OF";
            newRow["Congviec"] = "Kh«ng tham gia";
            newRow["Sothang"] = DateAndTime.DateDiff(DateInterval.Month, Convert.ToDateTime(newRow["Tuthang"].ToString().Substring(0, 4) + "/" + newRow["Tuthang"].ToString().Substring(4, 2) + "/01"),
              Convert.ToDateTime(newRow["Denthang"].ToString().Substring(0, 4) + "/" + newRow["Denthang"].ToString().Substring(4, 2) + "/01")) + 1;
            
            foundRows = dsKQuatrinh.Tables[0].Select("Sobhxh = '" + newRow["SOBHXH"].ToString().Trim() + "' and maqt = '" + newRow["Maqt"].ToString() + "'");

            dsKQuatrinh.Tables[0].Rows.InsertAt(newRow,dsKQuatrinh.Tables[0].Rows.IndexOf(foundRows[0]));

            FlxDetail_AfterRowColChange(null, null);

        }

        private void txtSolieuHN_Click(object sender, EventArgs e)
        {
            int i = 1;
            string queryString;
            Cursor.Current = Cursors.WaitCursor;
            
            queryString = "exec sp_executesql N'SELECT a.Sobhxh,c.Ho, c.Ten, c.Madvi,c.macv,d.diachi,d.tendvi "
            + " FROM HSC47_DTL b LEFT JOIN HOSOCN c ON b.Sobhxh=c.Sobhxh  "
            + " inner join MISBHXH_NT.dbo.DMDONVI d on c.Madvi = d.Madvi,"
            + " (SELECT Sobhxh, Ma_Nte, Loaidt, MAX(Maqt) AS Maqt FROM HSC47_DTL WHERE Madvi=@P1  AND LEFT(Maqt,6)=Denthang AND "
            + " LEFT(Maqt,6)<=@P2  AND CHARINDEX(Pa,''TT/TU/TN/GN/DN/CD'')=0 GROUP BY Sobhxh, Loaidt, Ma_Nte) a  "
            + " WHERE a.Sobhxh=b.Sobhxh AND a.Loaidt=b.Loaidt AND a.Ma_Nte=b.Ma_Nte AND a.Maqt=b.Maqt AND LEFT(b.Maqt,6)=b.Denthang "
            + " AND b.Madvi=@P3  AND b.Hsl+b.Pc1+b.Pc2+b.Pc3+b.Pc4+b.Pc5+b.Ml+b.Mlyt<>0 AND CHARINDEX(b.Pa,''TT/TU/TN/GN/DN/CD'')=0 AND CHARINDEX(''" + Settings.Default.MaTam + "'',A.SOBHXH) = 0  order by a.Sobhxh',"
            + " N'@P1 varchar(7),@P2 varchar(6),@P3 varchar(7)', '" + txtMadviHN.Text + "A" + "', '" + ModuleBHXH.strMonths + "', '" + txtMadviHN.Text + "A" + "'";


            FlxSobhxh.Rows.Count = 1;
            FlxDetail.Rows.Count = 1;
            faQuaTrinh.Rows.Count = 1;
            intSochay = 0;
            using (SqlConnection connection =
                  new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = queryString;
                command.CommandTimeout = 3600;
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    FlxSobhxh.Rows.Count = FlxSobhxh.Rows.Count + 1;
                    //truong hop khong co nhap cong viec
                    if (reader["macv"].ToString().Trim() != "")
                    {
                        FlxSobhxh.Rows[i]["check"] = 1;
                    }
                  
                    if (reader["Madvi"].ToString().ToUpper() != txtMadviHN.Text + "A")
                    {
                        C1.Win.C1FlexGrid.CellStyle rs = this.FlxDetail.Styles.Add("rowcolor");
                        rs.ForeColor = Color.Red;
                        FlxSobhxh.Rows[i].Style = rs;
                    }
                    FlxSobhxh.Rows[i]["Madvi"] = reader["Madvi"];
                    FlxSobhxh.Rows[i]["Tendvi"] = reader["Tendvi"];
                    FlxSobhxh.Rows[i]["Sobhxh"] = reader["Sobhxh"];
                    FlxSobhxh.Rows[i]["Sobhxh1"] = reader["Sobhxh"].ToString().Trim().Substring(6);
                    FlxSobhxh.Rows[i]["Ho"] = reader["Ho"];
                    FlxSobhxh.Rows[i]["Ten"] = reader["Ten"];
                    FlxSobhxh.Rows[i]["macv"] = reader["macv"];
                    FlxSobhxh.Rows[i]["Diachi"] = reader["Diachi"];
                    FlxSobhxh.Rows[i]["Tuthang"] = "201301";
                    FlxSobhxh.Rows[i]["Denthang"] = "201312";
                    FlxSobhxh.Rows[i]["Xacnhan"] = "QT";
                    i++;

                }
                reader.Close();
            }
            Cursor.Current = Cursors.Default;
        }

        private void txtKiemtraHN_Click(object sender, EventArgs e)
        {   
            btnkiemtra_Click(null, null);
        }

        private void txtTaotoroiHN_Click(object sender, EventArgs e)
        {
            btnTaotoroi_Click(null, null);
        }

        private void btnDS_Click(object sender, EventArgs e)
        {
            DataRow newRow;
            dsIntoroi.Tables["DSTOROI"].Clear();
            for (int i = 1; i < FlxDetail.Rows.Count; i++)
            {
                if (Convert.ToInt16(FlxDetail.Rows[i]["CHECK"]) == 1)
                {
                    newRow = dsIntoroi.Tables["DSTOROI"].NewRow();
                    newRow["SOBHXH"] = FlxDetail.Rows[i]["SOBHXH"];
                    newRow["HOTEN"] = FlxDetail.Rows[i]["HO"].ToString().Trim() + " " + FlxDetail.Rows[i]["TEN"].ToString().Trim();
                    newRow["TUTHANG"] = ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["TUTHANG"].ToString());
                    newRow["DENTHANG"] = ModuleBHXH.FormatThangNam(FlxDetail.Rows[i]["DENTHANG"].ToString());
                    newRow["MADVI"] = FlxDetail.Rows[i]["MADVI"];
                    newRow["TENDVI"] = FlxDetail.Rows[i]["TENDVI"];
                    newRow["DIACHIDVI"] = FlxDetail.Rows[i]["DIACHI"];
                    dsIntoroi.Tables["DSTOROI"].Rows.Add(newRow);

                }
            }
            Report f = new Report();
            ReportDocument cr = new ReportDocument();
            cr.Load("crpDSCaptoroi.rpt");
            cr.SetDataSource(dsIntoroi);
            foreach (CrystalDecisions.CrystalReports.Engine.FormulaFieldDefinition thisFormulaField in cr.DataDefinition.FormulaFields)
            {
                switch (thisFormulaField.Name)
                {
                    case "truongphong":
                        thisFormulaField.Text = "' §íi Duy Xu©n '";
                        break;

                }
            }
            f.crpView.ReportSource = cr;
            f.Show();
        }

        private void btnBB_Click(object sender, EventArgs e)
        {
            DataRow newRow;
            int i,sodiem = 0;
            dsIntoroi.Tables["BB"].Clear();
            for (i = 1; i < FlxDetail.Rows.Count; i++)
            {
                if (Convert.ToInt16(FlxDetail.Rows[i]["CHECK"]) == 1)
                {
                    if (FlxDetail.Rows[i]["MADVI"].ToString() != FlxDetail.Rows[i - 1]["MADVI"].ToString() && i != 1)
                    {
                        newRow = dsIntoroi.Tables["BB"].NewRow();
                        newRow["MADVI"] = FlxDetail.Rows[i-1]["MADVI"];
                        newRow["TENDVI"] = FlxDetail.Rows[i-1]["TENDVI"];
                        newRow["DIACHIDVI"] = FlxDetail.Rows[i-1]["DIACHI"];
                        newRow["TONGTOROI"] = sodiem;
                        newRow["TONGTOROICHU"] = ModuleBHXH.Doc_tien_sang_tieng_viet(sodiem) + "tê rêi";
                        dsIntoroi.Tables["BB"].Rows.Add(newRow);
                        sodiem = 1;
                    }
                    else
                    {
                        sodiem++;
                    }
                }
            }
            newRow = dsIntoroi.Tables["BB"].NewRow();
            newRow["MADVI"] = FlxDetail.Rows[i - 1]["MADVI"];
            newRow["TENDVI"] = FlxDetail.Rows[i - 1]["TENDVI"];
            newRow["DIACHIDVI"] = FlxDetail.Rows[i - 1]["DIACHI"];
            newRow["TONGTOROI"] = sodiem;
            newRow["TONGTOROICHU"] = ModuleBHXH.Doc_tien_sang_tieng_viet(sodiem) + "tê rêi";
            dsIntoroi.Tables["BB"].Rows.Add(newRow);

            Report f = new Report();
            ReportDocument cr = new ReportDocument();
            cr.Load("crpGroupBBGiaonhanToRoi.rpt");
            cr.SetDataSource(dsIntoroi);
            foreach (CrystalDecisions.CrystalReports.Engine.FormulaFieldDefinition thisFormulaField in cr.DataDefinition.FormulaFields)
            {
                switch (thisFormulaField.Name)
                {

                    case "TenCty":
                        thisFormulaField.Text = "'" + Settings.Default.Congty + "'";
                        break;
                    case "Diachi":
                        thisFormulaField.Text = "'" + Settings.Default.DiaChi + "'";
                        break;
                    case "truongphong":
                        thisFormulaField.Text = "'" + Settings.Default.Thutruong + "'";
                        break;

                }
            }
            f.crpView.ReportSource = cr;
            f.Show();

        }

       
    }

        
            
    
}



